I'm working on application where I need to append a new line when i touch the button on iPhone. I did this all but every time it writes over what i have written.
How to append a new line each time I press the button save.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myAge: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// get the documents folder url
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func writeNow(sender: UIButton) {
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent("fileForIphoneAbdulla.txt")
var text = myAge.text
do {
try text!.writeToURL(fileDestinationUrl, atomically: true, encoding: NSUTF8StringEncoding)
print("file is saved succefully")
do {
let mytext = try String(contentsOfURL: fileDestinationUrl, encoding: NSUTF8StringEncoding)
print(mytext) // "some text\n"
} catch let error as NSError {
print("error loading from url \(fileDestinationUrl)")
print(error.localizedDescription)
}
} catch let error as NSError {
print("error writing to url \(fileDestinationUrl)")
print(error.localizedDescription)
}
}
}