swift - NSAttributedString 在初始化时崩溃,但为什么呢?

标签 swift encoding nsattributedstring

有时这东西会崩溃,但我不知道为什么以及什么时候。 有人有想法吗?

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)

最佳答案

我强烈建议你升级到 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
    }
}

关于swift - NSAttributedString 在初始化时崩溃,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51191069/

相关文章:

json - Swift3:Openweather API 返回 nil 和 API 错误

sql - Postgres 将 LATIN1 编码的文件复制到 UTF 编码的表中

ios - UITextView 延迟滚动添加图像

ios - 无法将类型 'Range<String.Index>'(又名 'Range<String.CharacterView.Index>')的值转换为预期参数类型 'NSRange'(又名 '_NSRange')

ios - Firebase 存储为 url 返回 nil

ios - chartValueSelected 永远不会被调用

swift - UIBarButtonItem UIButton View alpha 不起作用

c# - 有人有阅读 ISOBUS (ISO 11783-10) 二进制时间日志文件的经验吗?

c# - 如何在日语窗口操作系统中对日语文本进行编码?

ios - 解析标记时 OHAttributedLabel 的格式问题