Swift 单击按钮后如何写入文件
我制作了一个简单的药物治疗程序,每次单击“服用药物”按钮,它都会将当前时间存储在Swift 单击按钮后如何写入文件,swift,macos,cocoa,foundation,Swift,Macos,Cocoa,Foundation,我制作了一个简单的药物治疗程序,每次单击“服用药物”按钮,它都会将当前时间存储在NSUserDefaults中。嗯,我想把它保存在一个文件中,这样我就可以记录我服用药物的所有日期和时间 单击按钮时如何写入文件?此外,我需要帮助或指导如何将其用于我正在尝试做的事情。我是Swift的新手,我正在努力边走边自学。试试这个: // Append a string to a file with a terminator that defaults to newline // Equivalent to W
NSUserDefaults
中。嗯,我想把它保存在一个文件中,这样我就可以记录我服用药物的所有日期和时间
单击按钮时如何写入文件?此外,我需要帮助或指导如何将其用于我正在尝试做的事情。我是Swift的新手,我正在努力边走边自学。试试这个:
// 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)
如果函数由于任何原因无法写入指定的文件,它将抛出一个错误
为什么不让函数接受路径作为
字符串(/path/to/file.log
),而不是URL
(file://path/to/file.log
)?苹果公司鼓励所有路径都用URL
表示,即使它们指向本地文件。许多较新的API只接受路径作为URLFileManager
是Objective-C遗留下来的旧功能。还有一些功能(如fileExists(atPath:)
)尚未转换为快速方式。这就是如何在特定URL处向文件追加新行,而不是写入它(因为写入将替换以前存储的内容)
用法
/// 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()
}
我建议从这里开始学习有关FileManager的基本知识:这给了我错误从这里抛出的错误无法处理这给了我错误:使用未解析标识符“路径”我需要一个关于如何使用此代码的分步指南。我甚至不知道如何使用扩展,我把它放在了类之外,然后做了一个按钮并添加了使用代码。当我运行它时,它表示路径未解析。
//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()
}