Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 333
Shmidt Avatar asked Jan 03 '15 12:01

Shmidt


2 Answers

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)")
}
like image 126
Airspeed Velocity Avatar answered Oct 16 '22 05:10

Airspeed Velocity


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")
like image 38
zombie Avatar answered Oct 16 '22 05:10

zombie