RTF file for string attribute

I am trying to read the contents of an RTF file in an attribute line, but attributedTextthere 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
    }
}

Update . I changed the 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 a failure on textView.attributedText = attributedTextsaying fatal error: unexpectedly found nil while unwrapping an Optional value. In the debugger, I see that attributedTextit is not equal to zero and contains text with attributes from the file.

+4
source share
2 answers

Instead of looking to see if the work is working in a debugging session, you are much better off writing code to handle the error properly:

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

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

Using:

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

Source: https://habr.com/ru/post/1569812/


All Articles