我正在尝试写入/读取该包,并使用 StackOverflow 中的以下引用:
How to access file included in app bundle in Swift?
这看起来是很好的代码并且应该可以正常工作。
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let fileURL = documentsDirectory.appendingPathComponent("file.txt")
do {
if try fileURL.checkResourceIsReachable() {
print("file exist")
} else {
print("file doesnt exist")
do {
try Data().write(to: fileURL)
} catch {
print("an error happened while creating the file")
}
}
} catch {
print("an error happened while checking for the file")
}
}
获取文件路径:
var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")
我可以保存文件,但不知何故我永远找不到文件路径
var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")
我无法获得任何扩展。我什至可以在 XCode 中的“设备”下的应用程序数据中看到保存的文件,这看起来很棒,但我无法通过 filePath
找到它。你能帮我吗?
最佳答案
好吧,让我们这样看:
Bundle.main
是您的应用程序;Bundle.main.url
在您的应用内部查找文件。 (这就是为什么链接的答案被称为“如何在 Swift 中访问包含在应用程序包中的文件?”)documentDirectory
位于您的应用的外部,即(明白这一点),它是文档目录。
因此,您将文件保存在您的应用外部,然后在您的应用内部查找该文件。那不是它所在的位置,所以这是行不通的。
关于swift - 尽管我正确保存了文件并看到了它,但为什么我无法获取文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083540/