I'm copy-pasting 2 post title returned by Wordpress API:
Haydarpaşa’da ortaya çıktı! Tam 1700 yıllık…
Pakistan’da terör saldırısı
I create structs for categories/posts and other things and made them decodable, but these do not handle Unicodes. Here is an example; the struct I created for categories. (Struct for posts is too big, so I share category struct. They're all built on the same idea.)
struct WPCategory: Decodable {
let id: Int
let count: Int
let description: String
let link: URL
let name: String
let slug: String
let taxonomy: WPCategoryTaxonomy
let parent: Int
enum WPCategoryTaxonomy: String, Codable {
case category, postTag = "post_tag", navMenu = "nav_menu", linkCategory = "link_category", postFormat = "post_format"
}
enum CodingKeys: String, CodingKey {
case id, count, description, link, name, slug, taxonomy, parent, meta
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
count = try container.decode(Int.self, forKey: .count)
description = try container.decode(String.self, forKey: .description)
let linkString = try container.decode(String.self, forKey: .link)
guard let link = URL.init(string: linkString) else {
throw WPAPIError.urlToStringFailed
}
self.link = link
name = try container.decode(String.self, forKey: .name)
slug = try container.decode(String.self, forKey: .slug)
taxonomy = try container.decode(WPCategoryTaxonomy.self, forKey: .taxonomy)
parent = try container.decode(Int.self, forKey: .parent)
}
}
I'm using Alamofire to get the data:
func getCategories(page: Int = 1, onCompletion completionHandler: @escaping (_ categories: [WPCategory]?, _ totalPages: Int?, _ error: Error?) -> Void) {
let request = alamofire.request(categoriesURL, method: .get, parameters: ["page": page, "per_page": 100, "exclude":"117"], encoding: URLEncoding.httpBody).validate()
request.responseData { (response) in
switch response.result {
case .success(let result):
guard let total = response.response?.allHeaderFields["x-wp-totalpages"] as? String else {
completionHandler(nil, nil, WPAPIError.couldNotFetchTotalHeader)
return
}
do {
let categories = try JSONDecoder.init().decode([WPCategory].self, from: result)
completionHandler(categories, Int(total), nil)
} catch(let err) {
completionHandler(nil, nil, err)
}
case .failure(let error):
completionHandler(nil, nil, error)
}
}
}
So, how can I handle these Unicode chars? Any ideas? Thank you.
from Swift and Wordpress API: Wordpress API escapes some characters to unicode
No comments:
Post a Comment