Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

ios - NSURLCache does not clear stored responses in iOS8

Here is the sample function I call when i need to clear cache and make a new call to URL

- (void)clearDataFromNSURLCache:(NSString *)urlString
{
    NSURL *requestUrl = [NSURL URLWithString:urlString];
    NSURLRequest *dataUrlRequest = [NSURLRequest requestWithURL: requestUrl];

    NSURLCache * cache =[NSURLCache sharedURLCache];


    NSCachedURLResponse* cacheResponse =[cache cachedResponseForRequest:dataUrlRequest];

    if (cacheResponse) {
        NSString* dataStr = [NSString stringWithUTF8String:[[cacheResponse data] bytes]];
        NSLog(@"data str r= %@",dataStr);
        NSLog(@"url  str r= %@",[[[cacheResponse response] URL] absoluteString]);
        [cache storeCachedResponse:nil forRequest:dataUrlRequest];
        [NSURLCache setSharedURLCache:cache];
    }

    [[NSURLCache sharedURLCache] removeCachedResponseForRequest:dataUrlRequest];

    //Check if the response data has been removed/deleted from cache
    NSURLRequest *finalRequestUrlRequest = [NSURLRequest requestWithURL:requestUrl];
    NSURLCache * finalCache =[NSURLCache sharedURLCache];

    NSCachedURLResponse* finalcacheResponse =[finalCache cachedResponseForRequest:finalRequestUrlRequest];

    if (finalcacheResponse) {
        //Should not enter here
        NSString* finaldataStr = [NSString stringWithUTF8String:[[finalcacheResponse data] bytes]];
        NSLog(@"data str r= %@",finaldataStr);
        NSLog(@"url  str r= %@",[[[cacheResponse response] URL] absoluteString]);
    }
}

In iOS 6/7 the response is deleted successfully for the requestURL, but in iOS 8 it never gets deleted. I have searched but could not find any reason why this should not work in iOS8.

Any help will be appreciated…..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NSURLCache is broken on iOS 8.0.x - it never purges the cache at all, so it grows without limit. See http://blog.airsource.co.uk/2014/10/11/nsurlcache-ios8-broken/ for a detailed investigation. Cache purging is fixed in the 8.1 betas - but removeCachedResponseForRequest: is not.

removeCachedResponsesSinceDate: does appear to work on iOS 8.0 - an API that was added for 8.0, but hasn't made it to the docs yet (it is in the API diffs). I am unclear what use it is to anyone - surely what you normally want to do is remove cached responses before a particular date.

removeAllCachedResponses works as well - but that's a real sledgehammer solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...