Сбой NSAttributedString при инициализации, но почему? - PullRequest
0 голосов
/ 05 июля 2018

Иногда эта штука падает, но я не знаю, почему и когда. У кого-нибудь есть идея?

extension String {
var htmlDecoded: String? {

    if let encodedData = self.data(using: String.Encoding.utf8) as Data? {
        let attributedOptions = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                  NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
        do {
            let attributedString = try NSAttributedString(data: encodedData,
                                                          options: attributedOptions,
                                                          documentAttributes: nil)
            return attributedString.string

        } catch let error as NSError {
            print("ERROR: ", error.localizedDescription)

            return self
        }
    }
    return self
}
}

Это ошибка, которую я получаю от HockeyApp

function signature specialization <Arg[0] = Owned To Guaranteed and Exploded> of @nonobjc (extension in UIKit):__C.NSAttributedString.init(data: Foundation.Data, options: [Swift.String : Any], documentAttributes: Swift.AutoreleasingUnsafeMutablePointer<__C.NSDictionary?>?) throws -> __C.NSAttributedString (String+html.swift:0)

function signature specialization <Arg[0] = Exploded> of (extension in Podcat_2):Swift.String.htmlDecoded.getter : Swift.String? (String+html.swift:0)

1 Ответ

0 голосов
/ 05 июля 2018

Я настоятельно рекомендую вам перейти на swift 4. Шрифт сильно изменился в swift 4, и лучше сделать это раньше.

Вот моя версия swift 4, которая отлично работает для меня, чтобы преобразовать строку html в NSAttributedString. Затем вы можете вызвать .string, чтобы получить саму строку.

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        return html
    }
}
...