0

I am trying to create a simple text input application in Swift, which this is my very first application created in this particular language. I am able to create a file and save text to it. The quest that I am on now to find an answer is the following:

How do I save multiple entries from my NSTextField to the same file with a time stamp of the entry? Because every time I hit save, it overwrites the file with the new entry.

The following is my code:

    @IBAction func saveTaskButtonClicked(_ sender: NSButton) {
    //save task function
    do {
        // get the documents folder url
        if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            // create the destination url for the text file to be saved
            let fileURL = documentDirectory.appendingPathComponent("msrfile.txt")
            // define the string/text to be saved
            let text = taskEntry.stringValue
            // writing to disk
            // Note: if you set atomically to true it will overwrite the file if it exists without a warning
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
            print("saving was successful")
            // any posterior code goes here
            // reading from disk
            let savedText = try String(contentsOf: fileURL)
            print("savedText:", savedText)   // "Hello World !!!\n"
        }
    } catch {
        print("error:", error)
    }
}

Edit (Found solution):

The following is my updated code

    @IBAction func saveTaskButtonClicked(_ sender: NSButton) {
    //save task function
    do {
        // get the documents folder url
        if let documentDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first {
            // create the destination url for the text file to be saved
            let fileURL = documentDirectory.appendingPathComponent("msrfile.txt")
            // define the string/text to be saved
            let text = taskEntry.stringValue + " " + dateOfTaskEntry.stringValue + "\n"
            let encoding = String.Encoding.utf8

            guard let data = text.data(using: encoding) else {
                throw FileWriteError.convertToDataIssue
            }
            if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
                fileHandle.seekToEndOfFile()
                fileHandle.write(data)
            } else {
                try text.write(to: fileURL, atomically: false, encoding: encoding)
            }
            print("saving was successful")
            // any posterior code goes here
            // reading from disk
            let savedText = try String(contentsOf: fileURL)
            print("savedText:", savedText)   // "Hello World !!!\n"
        }
    } catch {
     print("error:", error)
    }
}
4
  • Consider to use a serializable text format like Property List or JSON to be able to save timestamp and text separately in a collection type or custom struct.
    – vadian
    Mar 30, 2019 at 19:41
  • Perhaps stackoverflow.com/questions/27327067/… Mar 30, 2019 at 20:23
  • I should have stated that the link you shared is the original post where I found this solution. But it is overwriting when I try and add new text to it
    – gwatson117
    Mar 30, 2019 at 21:10
  • link to my code if you want to take a look at it and run the app on your desktop to see.
    – gwatson117
    Mar 30, 2019 at 21:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.