我正在复制粘贴 Wordpress API 返回的 2 个帖子标题:
Haydarpaşa’da ortaya çıktı! Tam 1700 yıllık…
巴基斯坦’da terör saldırısı
我为类别/帖子和其他内容创建结构并使其可解码,但这些不处理 Unicode。这是一个例子;我为类别创建的结构。 (帖子结构太大,所以我共享类别结构。它们都是基于相同的想法构建的。)
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)
}
}
我正在使用 Alamofire 来获取数据:
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)
}
}
}
那么,我该如何处理这些 Unicode 字符呢?有任何想法吗?谢谢。
最佳答案
使用我为其编写的扩展:
extension String {
func htmlDocument() throws -> String {
let data = self.data(using: .unicode)
let options: [NSAttributedString.DocumentReadingOptionKey: NSAttributedString.DocumentType] = [.documentType : .html]
return try NSAttributedString(data: data!, options: options, documentAttributes: nil).string
}
}
因此您可以在解码器中使用它,例如:
...
name = try container.decode(String.self, forKey: .name).htmlDocument()
...
关于ios - Swift 和 WordPress API : Wordpress API escapes some characters to unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56092716/