在Swift 4中将属性文本转换为HTML [英] Convert attributed text to HTML in Swift 4

查看:712
本文介绍了在Swift 4中将属性文本转换为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Swift 4中将属性文本转换为HTML,以便它可以存储在Firebase / Firestore中,并在不同设备/平台之间同步。我已阅读每一篇文章,我可以找到Stackoverflow包括转换属性的字符串,, ;简单"标签html 转换属性文本为HTML 和本博客文章:< a href =http://sketchytech.blogspot.com/2016/02/swift-from-html-to-nsattributetext-and.html =nofollow noreferrer> http://sketchytech.blogspot.com/2016/2016 /02/swift-from-html-to-nsattributedtext-and.html 。我发现Swift 4.x在NSDocumentTypeDocumentAttribute和NSHTMLTextDocumentType中引发了一个未解决的标识符错误,这些错误代码示例中有(下例)。这些错误不会在Swift 3.x中抛出。 Xcode建议我可能会使用NSDocumentTypeDocumentOption,但不提供修复,我不确定这是否是我想要的或如何使用它。

I am trying to convert attributed text to HTML in Swift 4 so that it can be stored in Firebase/Firestore and synced across different devices/platforms. I have read every article I can find on Stackoverflow including Convert attributed string, to, "simple" tagged html, Convert attributed text to HTML and this blog article: http://sketchytech.blogspot.com/2016/02/swift-from-html-to-nsattributedtext-and.html. I am finding that Swift 4.x throws an unresolved identifier error for NSDocumentTypeDocumentAttribute and NSHTMLTextDocumentType in the various code examples there are (example below). These errors are not thrown in Swift 3.x. Xcode suggests that I might mean to use NSDocumentTypeDocumentOption but does not offer a fix and I am not sure if that is what I want or how to use it if it is.

let myAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.green ]
let attrString = NSAttributedString(string: "Hello.", attributes: myAttributes)
let x = attrString
var resultHtmlText = ""
do {

    let r = NSRange(location: 0, length: x.length)
    let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

    let d = try x.data(from: r, documentAttributes: att)

    if let h = String(data: d, encoding: .utf8) {
        resultHtmlText = h
    }
}
catch {
    print("utterly failed to convert to html!!! \n>\(x)<\n")
}
print(resultHtmlText)

感谢您的帮助

推荐答案

对于Swift 4.x,行:

For Swift 4.x, the line:

let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

应该是:

should be:

let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]

这篇关于在Swift 4中将属性文本转换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆