简体   繁体   English

在Swift 4中将属性文本转换为HTML

[英]Convert attributed text to HTML in Swift 4

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. 我正在尝试将属性文本转换为Swift 4中的HTML,以便它可以存储在Firebase / Firestore中并在不同的设备/平台上同步。 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 . 我已经阅读了我在Stackoverflow上可以找到的每篇文章,包括转换属性字符串,“简单”标记的html将属性文本转换为HTML以及此博客文章: 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). 我发现Swift 4.x在各种代码示例中抛出了NSDocumentTypeDocumentAttribute和NSHTMLTextDocumentType的未解析标识符错误(例如下面的例子)。 These errors are not thrown in Swift 3.x. 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. Xcode建议我可能意味着使用NSDocumentTypeDocumentOption但不提供修复,我不确定这是否是我想要的或如果它是如何使用它。

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)

Thanks for your help 谢谢你的帮助

For Swift 4.x, the line: 对于Swift 4.x,该行:

let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

should be: 应该:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM