NSURLCache, set user key

I am using NSURLCache and I would like to set a user key for NSURLRequest. Is it possible?

Full explanation:

I am developing a mapping application that uses OpenStreetMap tiles. OpenStreetMap provides several fragment serving servers to reduce the load on each server. I use these servers randomly. So, for example, the following URLs will provide the same snippet:

Obviously, this causes some problems for my caching, because if I cache a fragment from server A, next time if I try to load from server B, NSURLCache will not find the fragment.

So, I would like to set a cache key for myself to handle this. Is it possible?

+4
source share
2 answers

You can subclass NSURLCache and override implementations cachedResponseForRequest:and storeCachedResponse:forRequest:, and then use setSharedURLCache:to set it to your subclass.

The easiest way is probably to call superfor storage (or not overriding), but then in the search, if it is a request for a fragment, check all the possibilities (using super) and return the answer if you get not zero.

+5
source

, , , NSURLCache, , "" : , / . :

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));
    }
}

:

let cache = CustomNsUrlCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 100 * 1024 * 1024, diskPath: nil);
NSURLCache.setSharedURLCache(cache);

:

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();
}
+2

All Articles