Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load rtf file into UITextView in Swift 2

Can somebody help me to load an rtf text into UITextView with Swift 2? The answers I've gotten are old and out of date. The text is instructions on how to play the game I'm writing in an app. So far, all I've been able to do is to copy and paste all the rtf text into the placeholder box. This works for iPhones in the simulator, but when trying it in the iPad simulator or iPhone 6 Plus there appears double vertical scroll bars when I do this. It looks messy.

I also now have a real plain text of the same file, so we can try that too.

like image 844
Edward_JS Avatar asked Feb 29 '16 04:02

Edward_JS


2 Answers

Swift 3

        if let rtfPath = Bundle.main.url(forResource: "SomeTextFile", withExtension: "rtf") {
            do {
                let attributedStringWithRtf:NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
                self.textView.attributedText = attributedStringWithRtf
            } catch let error {
                print("Got an error \(error)") 
            }
        }

Swift 4 & 5

    if let rtfPath = Bundle.main.url(forResource: "someRTFFile", withExtension: "rtf") {
        do {
            let attributedStringWithRtf: NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
            self.textView.attributedText = attributedStringWithRtf
        } catch let error {
            print("Got an error \(error)")
        }
    }
like image 94
MikeG Avatar answered Oct 02 '22 05:10

MikeG


Swift 3 Code:

if let rtfPath = Bundle.main.url(forResource: "description_ar", withExtension: "rtf") {
    do {
        let attributedStringWithRtf:NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
            self.textView.attributedText = attributedStringWithRtf
        } catch {
            print("We got an error \(error)") //or handle how you want
        }
}

Edits and updates inspired by @MikeG
October 21 update inspired by @RAJAMOHAN-S and @biomiker

like image 31
Chucky Avatar answered Oct 02 '22 04:10

Chucky