RTF 文件到属性字符串

RTF file to attributed string

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

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
    }
}

Upd.: 我将代码更改为:

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

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


        textView.attributedText = attributedText

}

现在 textView.attributedText = attributedText 上出现崩溃说:fatal error: unexpectedly found nil while unwrapping an Optional value。我在调试器中看到 attributedText 不是 nil 并且包含带有文件属性的文本。

与其查看调试器中的操作 worked/failed,不如编写代码来适当地处理失败:

if let attributedText = NSAttributedString(fileURL: fileURL, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: &error) {
    textView.attributedText = attributedText
}
else if let error = error {                
    println(error.localizedDescription)
}

Swift 4

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

Swift 4 @available(iOS 7.0, *)

func loadRTF(from resource: String) -> NSAttributedString? {
    guard let url = Bundle.main.url(forResource: resource, withExtension: "rtf") else { return nil }

    guard let data = try? Data(contentsOf: url) else { return nil }

    return try? NSAttributedString(data: data,
                                   options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf],
                                   documentAttributes: nil)
}

用法:

textView.attributedText = loadRTF(from: "FILE_HERE_WITHOUT_RTF")