加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – RTF文件到属性字符串

发布时间:2020-12-14 04:42:04 所属栏目:百科 来源:网络整理
导读:我正在尝试将RTF文件内容读取为属性字符串,但attributesText为零.为什么? if let fileURL = NSBundle.mainBundle().URLForResource(filename,withExtension: "rtf") { var error: NSError? if let attributedText = NSAttributedString(fileURL: fileURL,op
我正在尝试将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)")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读