尽管如此,NSUrlsession被解雇了,网址没有被调用

时间:2017-05-28 12:20:29

标签: ios nsurlsession invalidation

我有这种从URL获取JSON数据的方法:

-(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];
}

在myViewController中,viewWillAppear我这样调用这个方法:

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

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

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

}

这很好,但只有ONCE:

当我离开myViewController并再次输入时,

  • 调用viewWillAppear,然后按顺序
  • [self getJsonResponse:...被称为
  • 执行成功块中的代码

但是:我注意到,监控Charles的网络活动,没有调用my.valid.url。

是什么给出的?我应该使共享会话无效吗?如果是的话,何时?

1 个答案:

答案 0 :(得分:1)

将NSURLSessionConfiguration chachePolicy设置为NSURLRequestReloadIgnoringCacheData,然后重试。这是了解Http-caching的好resource。阅读Apple指南中提供的文档。

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