Converting NSAttributedString to Storage Data
I have it UITextView
with a text attribute and allowsEditingTextAttributes
set to true
.
I am trying to convert an attributed string to 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 throws the following error:
Error Domain=NSCocoaErrorDomain Code=66062 "(null)"
Any ideas what this error means or what might be causing this? I am on the latest Xcode and iOS. Thank.
+4
source to share
1 answer
You need to specify which document data type you want 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
let textView = UITextView()
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont(name: "Helvetica", size: 16)!]
textView.attributedText = NSAttributedString(string: "abc", attributes: attributes)
if let attributedText = textView.attributedText {
let documentAttributes: [NSAttributedString.DocumentAttributeKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
do {
let htmlData = try attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: documentAttributes)
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>
*/
+6
source to share