我正在尝试使用以下代码将属性字符串转换为Data对象:
let text = self.textVIEw.attributedTextlet data = try text.data(from: NSMakeRange(0,text.length),documentAttributes: [:])
但是,这会引发以下错误:
Error Domain=NSCocoaErrorDomain Code=66062 "(null)"
任何想法这个错误意味着什么或可能导致这个?我正在使用最新的Xcode和iOS.谢谢.
解决方法 您需要指定要将属性字符串转换为哪种文档数据:NSPlainTextdocumentType // Plain text document. .txt documentNSHTMLTextdocumentType // Hypertext MarkuP Language .HTML document.NSRTFTextdocumentType // Rich text format document. .rtf document.NSRTFDTextdocumentType // Rich text format document with attachment. (.rtfd) document.
Xcode 8.3.2•Swift 3.1
let textVIEw = UITextVIEw()textVIEw.attributedText = NSAttributedString(string: "abc",attributes: [NSFontAttributename: UIFont(name: "Helvetica",size: 16)])if let attributedText = textVIEw.attributedText { do { let HTMLData = try attributedText.data(from: NSRange(location: 0,length: attributedText.length),documentAttributes: [NSdocumentTypedocumentAttribute: NSHTMLTextdocumentType]) let HTMLString = String(data: HTMLData,enCoding: .utf8) ?? "" } catch { print(error) }}
更新Xcode 9.0.1•Swift 4
let textVIEw = UITextVIEw()let attributes: [NSAttributedStringKey: 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,documentAttributes: documentAttributes) let HTMLString = String(data: HTMLData,enCoding: .utf8) ?? "" print(HTMLString) } catch { print(error) }}
这将打印
/* <!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 ><span >abc</span></p></body></HTML>*/总结
以上是内存溢出为你收集整理的ios – 将NSAttributedString转换为数据以进行存储全部内容,希望文章能够帮你解决ios – 将NSAttributedString转换为数据以进行存储所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)