0

我正在尝试写入/读取包,并使用 StackOverflow 中的以下参考:

如何在 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。你能帮我么?

4

1 回答 1

0

好吧,让我们这样看:

  • Bundle.main是您的应用程序;Bundle.main.url您的应用程序中查找文件。(这就是为什么链接的答案被称为“如何在 Swift中访问应用程序包中包含的文件?”)

  • 在您的应用documentDirectory程序之外,即(获取此),它是 Documents 目录。

因此,您将文件保存在应用程序之外,然后在应用程序查找文件。那不是它所在的地方,所以那是行不通的。

于 2019-05-10T19:10:34.400 回答