我有这种从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");
}];
}
效果很好,但仅一次:
当我离开myViewController并再次输入时,
依次调用viewWillAppear和
[self getJsonResponse:...被称为
执行成功块中的代码
但是,我注意到:通过Charles监视网络活动,没有调用my.valid.url。
是什么赋予了?我应该使共享会话无效吗?如果是这样,什么时候?
最佳答案
将NSURLSessionConfiguration chachePolicy设置为NSURLRequestReloadIgnoringCacheData
,然后重试。这是了解Http缓存的好方法resource。还要阅读苹果指南中提供的文档。
NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
config.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
关于ios - NSUrlsession被触发,未调用URL,但是结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44227253/