gpt4 book ai didi

swift - 在应用重新启动时保留简单的文本文件

转载 作者:行者123 更新时间:2023-11-28 15:00:55 26 4
gpt4 key购买 nike

我正在尝试使用以下内容来持久化一个简单的文件:

        if let documents = directories.first {
if let urlDocuments = URL(string: documents) {

let urlText = urlDocuments.appendingPathComponent("file.txt")
print(urlText)
do {
try text.write(to: urlText, atomically: false, encoding: .utf8)
print(text)
}
catch {}
true)

}
}

但无论我选择什么目录,它都会将其保存在类似的地方

/Users/jaredearl/Library/Developer/CoreSimulator/Devices/6D477D99-7741-472D-8D16-4AE6771AF92E/data/Containers/Data/Appli ... file.txt

那个标签在重新启动和我使用类似的东西时会发生变化:

let documents = "/Users/jaredearl/Desktop/"
if let urlDocuments = URL(string: documents) {

let urlText = urlDocuments.appendingPathComponent("file.txt")
print(urlText)
do {
try text.write(to: urlText, atomically: false, encoding: .utf8)
print(text)
}
catch {/* error handling here */}

}

然后,当我尝试读取文件时,我得到:NSURLConnection 已完成,但出现错误 - 代码 -1002

我怎样才能让它在重启后持续存在?

最佳答案

在 swift 3.0 中

你可以使用相同的函数来读/写文件

func storeSyncLog(txtStor:String) {
let fileName = "a.txt"
let dir = try? FileManager.default.url(for: .documentDirectory,in: .userDomainMask, appropriateFor: nil, create: true)
//If the directory was found, we write a file to it and read it back
if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") {
var inString = ""
do {
inString = try String(contentsOf: fileURL)
} catch {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}

//Write something in file

let outString = inString + "Date:\(Date()) yd : \(txtStor)\n\n"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
}

希望对你有帮助

关于swift - 在应用重新启动时保留简单的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com