Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/100.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 有时应用程序崩溃NSAttributedString将HTML转换为属性字符串_Ios_Swift_Nsattributedstring - Fatal编程技术网

Ios 有时应用程序崩溃NSAttributedString将HTML转换为属性字符串

Ios 有时应用程序崩溃NSAttributedString将HTML转换为属性字符串,ios,swift,nsattributedstring,Ios,Swift,Nsattributedstring,在将html转换为属性字符串时,应用程序很少崩溃 var htmlToAttributedString: NSAttributedString? { guard let data = data(using: .utf8) else { return NSAttributedString() } do { return try NSAttributedString(data: data, options: [.documentType: NS

在将html转换为属性字符串时,应用程序很少崩溃

var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    ```
不应从后台线程(即 是,选项字典包括NSDocumentTypeDocumentAttribute 具有NSHTMLTextDocumentType)的值

它将尝试与主线程同步、失败和超时。从主线程调用它是可行的(但是如果HTML包含对外部资源的引用,仍然可能超时,这应该不惜一切代价避免)。HTML导入机制旨在实现标记(即文本样式、颜色等)之类的功能,而不是用于一般的HTML导入。

尝试一下这种方法。 1.像这样创建数据类的扩展。

  • 和String类的另一个扩展

  • 像这样使用print((stringName.html2String)调用扩展名

  • 在UIViewRepresentable中使用Down将markdown转换为NSAttributedString时,我遇到了类似的问题

    我的解决方案是在DispatchQueue.main.async块中封装.toAttribute String()调用


    可能不是最干净的解决方案。但这是我发现的唯一有效的东西。

    我的代码和这个有什么区别??除了添加了数据扩展之外?发生时是否有崩溃日志?与崩溃无关,但如果您从未实际返回
    nil
    ,而是返回空字符串,则将变量声明为
    Optional
    ,则没有意义。