多次保存到定义的文件,而不会覆盖以前的数据

时间:2019-03-30 19:26:30

标签: swift cocoa xcode10.2

我正在尝试在Swift中创建一个简单的文本输入应用程序,这是我用这种特定语言创建的第一个应用程序。我能够创建一个文件并将文本保存到其中。我现在要寻找答案的任务如下:

如何将多个带有我的时间戳记的条目从我的NSTextField保存到同一文件?因为每次我单击保存时,它都会用新条目覆盖文件。

以下是我的代码:

    @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)
    }
}

编辑(找到的解决方案):

以下是我更新的代码

    @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)
    }
}

0 个答案:

没有答案