Shmidt
Shmidt

Reputation: 16664

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.

Upvotes: 11

Views: 5721

Answers (2)

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

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

Upvotes: 10

zombie
zombie

Reputation: 5259

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

Usage:

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

Upvotes: 2

Related Questions