【问题标题】:Why can't I get the filePath although I save my file properly and see it?为什么虽然我正确保存文件并看到它,但我无法获取 filePath?
【发布时间】:2019-09-28 17:07:42
【问题描述】:

我正在尝试写入/读取包,我使用 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 找到它。你能帮帮我吗?

【问题讨论】:

    标签: swift nsdocumentdirectory


    【解决方案1】:

    好吧,让我们这样看:

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

    • documentDirectory 在您的应用程序之外,即(得到这个),它是 Documents 目录。

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

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 2017-01-05
      • 2021-06-26
      • 2021-11-15
      • 1970-01-01
      • 2015-04-18
      • 2021-03-09
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多