So, I finally created my own NSURLCache, modifying its behavior completely, to a more "manual" mode: now, requests are not cached by default, but I can manually put/get responses with a custom key. Here is the code:
import Foundation
extension NSURLCache {
public func put(cachedResponse:NSCachedURLResponse, forKey key:String) {}
public func get(key:String) -> NSCachedURLResponse? { return nil; }
}
public class CustomNsUrlCache: NSURLCache {
// Prevent default caching:
public override func cachedResponseForRequest(request: NSURLRequest) -> NSCachedURLResponse? { return nil; }
public override func storeCachedResponse(cachedResponse: NSCachedURLResponse, forRequest request: NSURLRequest) {}
private func requestForKey(key:String) -> NSURLRequest {
let url:NSURL? = NSURL(string:"http://" + key);
return NSURLRequest(URL:url!);
}
public override func put(cachedResponse:NSCachedURLResponse, forKey key:String) {
super.storeCachedResponse(cachedResponse, forRequest:requestForKey(key));
}
public override func get(key:String) -> NSCachedURLResponse? {
return super.cachedResponseForRequest(requestForKey(key));
}
}
Don't forget to register the custom code in the app's delegate:
let cache = CustomNsUrlCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 100 * 1024 * 1024, diskPath: nil);
NSURLCache.setSharedURLCache(cache);
Usage:
if let cachedResponse = NSURLCache.sharedURLCache().get(cacheKey) {
// Use cached response
}
else {
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if let data = data, response = response {
// Cache the response:
NSURLCache.sharedURLCache().put(NSCachedURLResponse(response:response, data:data), forKey:cacheKey);
// Use the fresh response
}
else {
print(error);
}
};
task.resume();
}