iosswiftnsurlrequestappkitnsurlrequestcachepolicy

Stop NSURLRequest writing to cache


I have an iOS app that sends hundreds of HTTP requests per second using NSURLRequest. It's always over WiFi so performance is fine, and the content is different for every response so I've disabled caching via NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData:

let request = NSURLRequest(URL: requestURL,
      cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 0.1)

However, NSURLRequest is still writing the data to disk — hundreds of megabytes in just a few minutes.

This is especially concerning since my app is for data monitoring and may be left running for several hours at a time — and NSURLRequest is writing to the disk hundreds of times per second... I'm concerned flash memory can wear out under these conditions, even though I assume it has wear levelling.

How can I stop NSURLRequest from writing cache data to disk?


Solution

  • NSURLRequest's cache policy only controls if and how the cache will be read, not whether downloaded data will be written.

    If you're using NSURLRequest with NSURLSession, implement the URLSession(_:dataTask:willCacheResponse:completionHandler:) method in your delegate, and call the completionHandler with a nil argument.

    A similar delegate call works if you're using NSURLConnection; see this question for details.