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.

Welcome to The infinite monkey theorem

Somewhere a monkey just typed Shakespeare in TypeScript. Be the first to read the masterpieces (and the hilarious misfires) landing on the blog.

Subscribe to The infinite monkey theorem

We fling fresh posts—no banana peels attached—straight to your inbox.