如何在单击按钮后写入文件

问题描述 投票:-1回答:2

我做了一个简单的药物治疗计划,所有这一切都是每次我点击服用药物按钮,它存储当前时间在NSUserDefaults。好吧,我想把它放在哪里,而不是将日期和时间保存到文件中,这样我就可以记录所有日期和时间我服用药物。

单击按钮时如何写入文件?另外,我需要帮助或指导如何将它用于我正在尝试做的事情。我是斯威夫特的新手,我正在努力学习自己。

swift macos cocoa foundation
2个回答
0
投票

试试这个:

// Append a string to a file with a terminator that defaults to newline
// Equivalent to WriteLine in some other languages
func append(string: String, terminator: String = "\n", toFileAt url: URL) throws {
    // The data to be added to the file
    let data = (string + terminator).data(using: .utf8)!

    // If file doesn't exist, create it
    guard FileManager.default.fileExists(atPath: url.path) else {
        try data.write(to: url)
        return
    }

    // If file already exists, append to it
    let fileHandle = try FileHandle(forUpdating: url)
    fileHandle.seekToEndOfFile()
    fileHandle.write(data)
    fileHandle.closeFile()
}

let url = URL(fileURLWithPath: "/path/to/file.log")
try append(string: "Line 1", toFileAt: url)
try append(string: "Line 2", toFileAt: url)

如果由于任何原因无法写入指定的文件,该函数将抛出错误。


为什么不让函数接受路径为String/path/to/file.log)而不是URLfile://path/to/file.log)? Apple鼓励所有路径由URL代表,即使它们指向本地文件。许多较新的API仅接受path-as-URL。 FileManager是Objective-C的旧宿醉。还有一些函数(如fileExists(atPath:))尚未转换为Swifty方式。


0
投票

这是你可以如何将新行添加到特定URL的文件而不是写入它(因为写入将替换以前存储的内容)

extension String
    {
        func appendLineToURL(fileURL: URL) throws
        {
            try (self + "\n").appendToURL(fileURL: fileURL)
        }
        func appendToURL(fileURL: URL) throws
        {
            let data = self.data(using: String.Encoding.utf8)!
            try data.append(fileURL: fileURL)
        }
    }
    //MARK: NSData Extension
    extension Data
    {
        func append(fileURL: URL) throws {
            if let fileHandle = FileHandle(forWritingAtPath: fileURL.path)
            {
                defer
                {
                    fileHandle.closeFile()
                }

                fileHandle.seekToEndOfFile()
                fileHandle.write(self)
            }
            else
            {
                try write(to: fileURL, options: .atomic)
            }
        }
    }

用法

/// if want to add a New Line
let newLine = "your content\n"

/// if want to append just next to previous added line
let newLine = "your content"    
do
{
     //save
     try newLine.appendToURL(fileURL: path!)
}
catch
{
     //if error exists
     print("Failed to create file")
     print("\(error)")
}

更新这是我使用此功能的方式

//MARK: Usage
    func updateCsvFile(filename: String) -> Void
    {
        //Name for file
        let fileName = "\(filename).csv"
        let path1 = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDirectoryPath:String = path1[0]
        //path of file
        let path = NSURL(fileURLWithPath: documentDirectoryPath).appendingPathComponent(fileName)

        //Loop to save array //details below header
        for detail in DetailArray
        {
            let newLine = "\(detail.RecordString)\n"

            //Saving handler
            do
            {
                //save
                try newLine.appendToURL(fileURL: path!)
                showToast(message: "Record is saved")
            }
            catch
            {
                //if error exists
                print("Failed to create file")
                print("\(error)")
            }

            print(path ?? "not found")
        }
        //removing all arrays value after saving data
        DetailArray.removeAll()
    }
© www.soinside.com 2019 - 2024. All rights reserved.