我制作了一个简单的药物治疗计划,它所做的就是每次点击“服用药物”按钮,它会将当前时间存储在NSUserDefaults
。嗯,我想把它改为保存Date&到文件的时间,这样我就可以记录我服用药物的所有日期和时间。
单击按钮时如何写入文件?此外,我需要帮助或指导如何使用它来做我想做的事情。我是斯威夫特的全新人物,而且我在去的时候试着自己学习。
答案 0 :(得分: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
)而不是URL
(file://path/to/file.log
)的路径? Apple鼓励所有路径由URL
表示,即使它们指向本地文件。许多较新的API仅接受path-as-URL。 FileManager
是来自Objective-C的旧宿醉。还有一些函数(如fileExists(atPath:)
)尚未转换为Swifty方式。
答案 1 :(得分: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()
}