ios

fileExistsAtPath always returns NO (false)

Generating the path dynamically with NSSearchPathForDirectoriesInDomains.

The problem:

fileExistsAtPath always returns NO (even though the app container definitely contains the file).

We used to save some files in the Cache folder and persist the file path into a sqlite table. The URL to the file to be saved was stored in NSURL and .path would return the path. Here is an example:

/var/mobile/Containers/Data/Application/A586EFC6-EBA4-499F-A3F5-BA505CA44696/Library/Caches/OurFiles/ea347f7c-e25d-4538-9f0a-f83b22a66a7c

Later, we would check if the file is still there using fileExistsAtPath:

if ([[NSFileManager defaultManager] fileExistsAtPath:path])

We tested it and it all worked just fine. But a couple of weeks ago we accidentally discovered that fileExistsAtPath always returned NO.

There are at least two problems with our approach:

  • Caches folder might change for future iOS versions.
  • Unlike absoluteString, NSUrl path does not contain the scheme.

The solution:

Now we only store the name of the file (and not the full path) and generate the path dynamically with NSSearchPathForDirectoriesInDomains and it works just fine.

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox