问题:Swift 和 Wordpress API:Wordpress API 将一些字符转义为 unicode

我正在复制粘贴 Wordpress API 返回的 2 个帖子标题:

Haydarpaşa’da ortaya çıktı! Tam 1700 yıllık…

Pakistan’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()
...
Logo

更多推荐