Always getting back cached data in NSURLSessionDat

2019-05-03 16:11发布

问题:

I'm facing a very strange issue when using NSURLSessionDataTask to post a JSON request to the server.

The first request goes through and I receive the correct JSON response, when I do a second request I'm getting always back the old response and the server never receives the request. Even if I turn on airplane mode the NSURLSessionDataTask does work an I get back the old response again.

That's the code I'm using:

- (void)getJSONFromURL:(NSURL*)url identifierCode:(NSInteger)code
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:[DataController sharedInstance].currentUser.userToken forHTTPHeaderField:@"User-Token"];
[request setHTTPMethod:@"GET"];

if (![SVProgressHUD isVisible])
    [SVProgressHUD show];

NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    [self handleResponse:httpResponse withJSON:json identifierCode:code];

    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}];

[postTask resume];

}

回答1:

I've found the issue, I don't know why this has changed, because I never had to set that property before. Anyway I set configuration.URLCache = NULL; and now everthing works fine again.



回答2:

you can set

request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

to disable it per request