Search code examples
iosnsurlsessioninvalidation

NSUrlsession fired, url not called, nevertheless result


I have this method for getting JSON data from a URL:

-(void)getJsonResponse:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:urlStr];

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    //NSLog(@"%@",data);
                                                    if (error) {
                                                        failure(error);
                                                        NSLog(@"Error: %@", [error localizedDescription]);
                                                    }
                                                    else {
                                                        NSDictionary *json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                                        //NSLog(@"%@",json);
                                                        success(json);
                                                    }
                                                }];
    [dataTask resume];
}

In myViewController, viewWillAppear I call this method as such:

NSString * URLString = @"my.valid.url";

    [self getJsonResponse:URLString success:^(NSDictionary *result) {
       //here some code when succesful

    } failure:^(NSError *error) {
        NSLog(@"Something terrible happened");
    }];

}

That works fine, but only ONCE:

When I leave myViewController, and enter it again,

  • viewWillAppear is called, and subsequentially
  • [self getJsonResponse:... is called
  • my code in the success block is executed

However: monitoring the network activity with Charles, I notice, that no call is made to my.valid.url.

What gives? Should I invalidated the shared session? If so, when?


Solution

  • set NSURLSessionConfiguration chachePolicy to NSURLRequestReloadIgnoringCacheData and try again. Here is the good resource to understand about Http-caching. Read documentation given in apple guide as well.

    NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
    config.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];