I'm using ASIHttpRequests
and an ASINetworkQueue
in an ipho开发者_StackOverflow社区ne app to retrieve some 100k XML files and a lot of thumbnails from a web service. I'd like to cache the requests in the style of NSURLCache
. ASI doesn't seem to support caching as is, and I looked at the code and it drops to C to create the requests, so inserting the NSURLCache
layer seemed tricky.
What's the best way to implement this?
ASIHTTPRequest now supports caching - check out ASIDownloadCache ie.
[ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]]
You could provide your own caching before dropping down into ASI code.
Wrap your ASI code in a class that has a method:
-(NSString *)getContentFor:(NSURL *)url
That method first checks an internal NSDictionary to see if it has a key present for the specified url. If it does, it returns the object stored with the key.
If it doesn't, it performs the normal ASIRequest. When the request is received from the server, it stores it as a string in your dictionary with the key of the url.
Of course, you'll need to handle asynchronous requests and expiring of old requests with care.
Anyone asking how they can do this with ASIHTTPRequest directly may be interested in this branch of the code that adds support for this feature as an option.
NSURLConnection has support for caching in the style of NSURLCache, and it does a lot of work for you behind the scenes. It even has a nice delegate method that will allow you to manipulate the cachedResponse:
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
try this, it works for me.
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy];
[request setSecondsToCache:60*60*24]; // Cache for 24 hrs
[request setDelegate:self]; // A delegate must be specified
[request setCompletionBlock:^{
精彩评论