Search code examples
iosobjective-cnsurlsessionnsurlcache

How to cache NSUrlSession response data


I know that this question is ask many time, but all those are not solved my problem. I want to cache Webservice Data which I getting in from a URl. If cached data available then load data from the cache and with that in background thread it also checks if data is changed then cache update and data load with new data. I tried following code but nothing work.

-(void)getcountrylist
{
    [self setSharedCacheForImages];

    NSString *urlString = @"https://restcountries.eu/rest/v1/all";

    NSURLSession *session = [self prepareSessionForRequest];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"GET"];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSArray *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            dispatch_async(dispatch_get_main_queue(), ^{

               NSLog(@"Result new = %@",jsonResponse);

            });
        }
    }];
    [dataTask resume];
}

- (NSURLSession *)prepareSessionForRequest
{
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    [sessionConfiguration setHTTPAdditionalHeaders:@{@"Content-Type": @"application/json", @"Accept": @"application/json"}];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

    return session;
}

- (void)setSharedCacheForImages
{
    NSUInteger cashSize = 250 * 1024 * 1024;
    NSUInteger cashDiskSize = 250 * 1024 * 1024;
    NSURLCache *imageCache = [[NSURLCache alloc] initWithMemoryCapacity:cashSize diskCapacity:cashDiskSize diskPath:@"https://restcountries.eu/rest/v1/all"];

    [NSURLCache setSharedURLCache:imageCache];   
}

Solution

  • You can handle cache data using NSMutableURLRequest class setCachePolicy method. There are many methods works accordingly have a look.

    NSURLRequestReloadIgnoringCacheData: This methods ignores cache data and fetch the fresh updated response from server.

    Specifies that the data for the URL load should be loaded from the originating source. No existing cache data should be used to satisfy a URL load request.

    NSURLRequestUseProtocolCachePolicy: Specifies that the caching logic defined in the protocol implementation, if any, is used for a particular URL load request. This is the default policy for URL load requests.

    NSURLRequestReloadIgnoringLocalAndRemoteCacheData: Specifies that not only should the local cache data be ignored, but that proxies and other intermediates should be instructed to disregard their caches so far as the protocol allows.

    Some more check here: source.

    Uses:

    NSURLRequest *Request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLForService_Providers] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    

    OR

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];