Swift 3.0 FileManager.fileExists(atPath:) always return false

前端 未结 7 2134
一向
一向 2021-02-05 00:38

When I use method .fileExists(atPath:)to judge whether the file is exist in file system, the method always return false to me. I checked the file system and the fil

7条回答
  •  独厮守ぢ
    2021-02-05 01:11

    I want to share my experience, in case anyone else gets baffled by this.

    Tested on iOS 10-11, Xcode 9.2 and Swift 3.2.

    Short answer: if you save a file path to disk, you may solve by not including the Documents directory in it. Instead, every time you need to retrieve the file with the saved path, get the Documents directory and append the path.


    For an iOS app, I was saving an image to .../Documents/Pictures through the relative URL, let's say url. As the image was saved, a path, let's say url.path, was saved too in a Core Data entity.

    When I later tried retrieving the image through FileManager.default.fileExists(atPath: url.path), it always returned false.

    I was testing the app on my iPhone. It turned out that, for some reason, every time I ran the app from Xcode, the app identifier folder changed!!

    So:

    • App opened from Xcode -> Image saved -> app closed -> app opened from physical device -> fileExists -> TRUE
    • App opened from Xcode -> Image saved -> app closed -> app opened from Xcode -> fileExists -> FALSE

    You can check if this is your case by getting and printing the Document folder path (or URL, it doesn't matter) and comparing it with the saved path (or URL). If you get something like this:

    • /var/mobile/Containers/Data/Application/5D4632AE-C432-4D37-A3F7-ECD05716AD8A/Documents..
    • /var/mobile/Containers/Data/Application/D09904C3-D80D-48EB-ACFB-1E42D878AFA4/Documents..

    you found the issue.

提交回复
热议问题