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.
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)")
}
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With