0

I am trying to write/read to the bundle and I use the below reference from StackOverflow:

How to access file included in app bundle in Swift?

which looks like good code and should work fine.

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")
   }
}

To get filepath:

var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")

I can save the file but somehow I can never find the file path by

var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")

I cannot get any of the extensions. I even can see the saved file in my app's data under Devices in XCode which looks great but I can't find it by filePath​. Can you please help me?

Gleb A.
  • 1,180
  • 15
  • 24
troia77
  • 101
  • 1

1 Answers1

0

Well, let's look at it this way:

  • Bundle.main is your app; Bundle.main.url looks for the file inside your app. (That's why the linked answer is called "How to access file included in app bundle in Swift?")

  • The documentDirectory is outside your app, namely (get this), it's the Documents directory.

So you are saving the file outside your app and then looking for the file inside your app. That's not where it is, so that's not going to work.

matt
  • 515,959
  • 87
  • 875
  • 1,141