Always getting back cached data in NSURLSessionDataTask

放肆的年华 提交于 2019-12-07 04:24:52

问题


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



来源:https://stackoverflow.com/questions/23679195/always-getting-back-cached-data-in-nsurlsessiondatatask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!