swiftnsattributedstringios7.1

RTF file to attributed string


I'm trying to read RTF file contents to attributed string, but attributedText is nil. Why?

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.: I changed code to:

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

}

Now there is crash on textView.attributedText = attributedText says: fatal error: unexpectedly found nil while unwrapping an Optional value. I see in debugger that attributedText is non nil and contains text with attributes from file.


Solution

  • Rather than looking to see if the operation worked/failed in the debugger, you’d be much better off writing the code to handle the failure appropriately:

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