0

I have a simple app with text field (email) and a submit button. I have the emails stored in a txt file every time the form is used. Currently, every time a new email comes in, the previous gets deleted. I would like to add the "new email" to next line. I believe the right word is append to the next line. Here's my code:

@IBOutlet weak var window: NSWindow!

@IBOutlet weak var emailField: NSTextField!

@IBAction func submitButton(sender: AnyObject) {
    let myText = self.emailField.stringValue + ("\r\n")
    let path = "/Users/my-user-name/Desktop/codes.txt"
    let dir = (path as NSString).stringByDeletingLastPathComponent
    do {
        try myText.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
    } catch let error as NSError {
        print("error loading from path \(path)")
        print(error.localizedDescription)
    }

func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application
}

func applicationWillTerminate(aNotification: NSNotification) {
    // Insert code here to tear down your application
}

Any help would be really appreciate it. Thank you for your time.

L C
  • 438
  • 2
  • 10
  • 28
surfertide
  • 11
  • 1
  • 4
  • 1
    You can do it as explained here: http://stackoverflow.com/questions/27327067/append-text-or-data-to-text-file-in-swift. In order to convert the String to data use myText.dataUsingEncoding(NSUTF8StringEncoding) – creativ Apr 12 '16 at 06:18
  • I don't have any clues as such, I just wanted to let you know that instead of `let path = "/Users/my-user-name/Desktop/codes.txt"` you can use `NSHomeDirectory()` which will give you the location of your home dir as a string, so you could say `let path = "\(NSHomeDirectory()/Desktop/codes.txt)"`. Just if you didn't know already :-) – pbodsk Apr 12 '16 at 06:19

0 Answers0