How to avoid system purging URLCache on low disk space

I want to use URLCache to make data (e.g. User, Session, Privileges objects) available when offline. I think it is better to manually saving data in file or UserDefaults because it will fit seamlessly with existing code that load stuff from URLs and without extra code.

One of my concern is this. In URLCache documentation, it says:

Note
In iOS, the on-disk cache may be purged when the system runs low on disk space, but only when your app is not running.

I don't want my on-disk cache to get purged on low disk space.

I browse around and see URLCache has a new initializer in iOS 13 that accepts a directory url for on-disk cache.

Code Block
convenience init(memoryCapacity: Int, diskCapacity: Int, directory: URL? = nil)

From my understanding, Caches directory gets purged on low disk space.

From File System Programming Guide:

In iOS 5.0 and later, the system may delete the Caches directory on rare occasions when the system is very low on disk space. This will never occur while an app is running. However, be aware that restoring from backup is not necessarily the only condition under which the Caches directory can be erased.

So, my question is, if I pass a URL that is not a Caches directory URL. Will my on-disk cache survive the low memory purge? If not, is there any other way to achieve it?

I have exactly the same question. Any findings on this? I want a persistent "offline-cache". Initially I thought about doing it myself to have full control over the data. But wondered, if what Apple offers is sufficient and less complex to implement.

So, my question is, if I pass a URL that is not a Caches directory URL. Will my on-disk cache survive the low memory purge?

I would plan on the URL passed into the on-disk cache to be tracked and purged also during a low memory situation.

I want a persistent "offline-cache".

NSURLCache is a general-purpose web cache. Its primary target ‘market’ is apps like Safari. What you’re looking for isn’t a cache, by definition [1]. NSURLCache doesn’t implement the semantics you need. You will need to write, or acquire, your own code for this.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] In a cache, the only downside to a cache miss is performance, which isn’t the case in your scenario.

How to avoid system purging URLCache on low disk space
 
 
Q