【问题标题】:How To Write To File After Button Is Clicked单击按钮后如何写入文件
【发布时间】:2018-05-03 00:16:17
【问题描述】:

我制作了一个简单的药物程序,它所做的就是每次单击“服用药物”按钮时都会将当前时间存储在 NSUserDefaults 中。好吧,我想把它改为将日期和时间保存到一个文件中,这样我就可以记录我服用药物的所有日期和时间。

单击按钮时如何写入文件?此外,我需要有关如何将其用于我正在尝试做的事情的帮助或指导。我是 Swift 的新手,我正在尝试自己学习。

【问题讨论】:

标签: swift macos cocoa foundation


【解决方案1】:

试试这个:

// 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) 而不是URL (file://path/to/file.log) 的路径? Apple 鼓励使用URL 表示所有路径,即使它们指向本地文件。许多较新的 API 只接受 path-as-URL。 FileManager 是来自 Objective-C 的旧宿醉。还有一些函数(如fileExists(atPath:))尚未转换为 Swifty 方式。

【讨论】:

  • 这给了我错误从这里抛出的错误没有被处理
【解决方案2】:

这就是你如何在特定 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()
    }

【讨论】:

  • 这给了我错误:使用未解析的标识符“路径”
  • 我需要有关如何使用此代码的分步指南。我什至不知道如何使用扩展,我把它放在课外,然后做了一个按钮并添加了使用代码。当我运行它时,它说路径未解析。
猜你喜欢
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多