Convert NSAttributedString into Data for storage

蹲街弑〆低调 提交于 2019-11-27 06:59:43

问题


I have a UITextView with attributed text and allowsEditingTextAttributes set to true.

I'm trying to convert the attributed string into a Data object, using the following code:

let text = self.textView.attributedText
let data = try text.data(from: NSMakeRange(0, text.length), documentAttributes: [:])

However, this is throwing the following error:

Error Domain=NSCocoaErrorDomain Code=66062 "(null)"

Any ideas what this error means or what could cause this? I'm on the latest Xcode and iOS. Thanks.


回答1:


You need to specify what kind of document data you would like to convert your attributed string to:


NSPlainTextDocumentType   // Plain text document. .txt document
NSHTMLTextDocumentType    // Hypertext Markup Language .html document.
NSRTFTextDocumentType     // Rich text format document. .rtf document.
NSRTFDTextDocumentType    // Rich text format document with attachment. .rtfd document.

update Xcode 10.2 • Swift 5 or later

let textView = UITextView()
textView.attributedText = .init(string: "abc",
                                attributes: [.font: UIFont(name: "Helvetica", size: 16)!])
if let attributedText = textView.attributedText {
    do {
        let htmlData = try attributedText.data(from: .init(location: 0, length: attributedText.length),
                                               documentAttributes: [.documentType: NSAttributedString.DocumentType.html])
        let htmlString = String(data: htmlData, encoding: .utf8) ?? ""
        print(htmlString)
    } catch {
        print(error)
    }
}

This will print

/* <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px Helvetica}
span.s1 {font-family: 'Helvetica'; font-weight: normal; font-style: normal; font-size: 16.00pt}
</style>
</head>
<body>
<p class="p1"><span class="s1">abc</span></p>
</body>
</html>
*/


来源:https://stackoverflow.com/questions/43313291/convert-nsattributedstring-into-data-for-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!