0

I have a UITextview showing certain text by calling rtf files. I want to let users to edit the text on UITextView and save the changes they made in rtf file.

Is there any way I can change the rtf file itself by changing the text on UITextView??

Kahsn
  • 1,045
  • 3
  • 15
  • 25

1 Answers1

2

If you want a save-as-you-type solution to the problem:

  1. Make your view controller conform to UITextViewDelegate
  2. Connect the text view's delegate to the view controller
  3. Add the following function to your view controller:

// Path to your RTF file
let url = NSBundle.mainBundle().URLForResource("my_document", withExtension: "rtf")!

func textViewDidChange(textView: UITextView) {
    let data = try! textView.attributedText.dataFromRange(NSMakeRange(0, textView.attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
    data.writeToURL(url, atomically: true)
}

This will save every keystroke to the file. No idea on the performance though. I have not tested this on a real iPhone. If it's too hard on the device, consider putting a time delay between saves or have an NSTimer to save every n seconds.

Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Sorry for late confirmation. I just tried and it works very well! I have a further question. Would there be any way I can revert the rtf file back to the original state when needed? The one way I can think is making two copies and letting users to just manipulate the second one. – Kahsn Mar 03 '16 at 20:19
  • 1
    You have to make a copy of the original file. Remember, every keystroke is a write to the file so you lose its previous state. – Code Different Mar 03 '16 at 22:55