微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – RTF文件到属性字符串

我正在尝试将RTF文件内容读取为属性字符串,但attributesText为零.为什么?

if let fileURL = NSBundle.mainBundle().URLForResource(filename,withExtension: "rtf") {
    var error: NSError?
    if let attributedText = NSAttributedString(fileURL: fileURL,options: [NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType],documentAttributes: nil,error: &error){
        textView.attributedText = attributedText
    }
}

更新:我将代码更改为:

if let fileURL = NSBundle.mainBundle().URLForResource(filename,withExtension: "rtf") {
    var error: NSError?

    let attributedText = NSAttributedString(fileURL: fileURL,options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType],error: &error)
        println(error?.localizedDescription)


        textView.attributedText = attributedText

}

现在textView.attributedText = attributedText上出现崩溃:致命错误:在展开Optional值时意外发现nil.我在调试器中看到,attributesText是非零的,包含带有文件属性的文本.

解决方法

而不是在调试器中查看操作是否有效/失败,您可以更好地编写代码来适当地处理失败:

if let attributedText = NSAttributedString(fileURL: fileURL,error: &error) {
    textView.attributedText = attributedText
}
else if let error = error {                
    println(error.localizedDescription)
}

斯威夫特4

do {
    let attributedString = try NSAttributedString(url: fileURL,options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf],documentAttributes: nil)
} catch {
    print("\(error.localizedDescription)")
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐