0

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)
    }
}
}
André Kuhlmann
  • 4,378
  • 3
  • 23
  • 42

1 Answers1

0

The high level file methods are made to write the entire file.

To append you can use an NSFileHandle. It has methods like seekToEndOfFile to move the file pointer to the end and then writeData to add data to the end of the file.

BTW, your sample code is in Swift but you're using the jquery tag. I assume you're looking for help in Swift?

Duncan C
  • 128,072
  • 22
  • 173
  • 272