Ios 已激发NSUrlsession,未调用url,但结果为
我有一种从URL获取JSON数据的方法:Ios 已激发NSUrlsession,未调用url,但结果为,ios,nsurlsession,invalidation,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 URLWithS
-(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中,ViewWill将出现,我将此方法称为:
NSString * URLString = @"my.valid.url";
[self getJsonResponse:URLString success:^(NSDictionary *result) {
//here some code when succesful
} failure:^(NSError *error) {
NSLog(@"Something terrible happened");
}];
}
这很好,但只有一次:
当我离开myViewController并再次输入它时
- 调用VIEWWILLEXPEND,然后
- 调用了[self getJsonResponse:…]
- 执行成功块中的我的代码
给出了什么?我应该使共享会话无效吗?如果是,什么时候?将NSURLSessionConfiguration设置为
NSURLrequestReloadingCacheData
,然后重试。以下是了解Http缓存的好方法。请阅读《apple指南》中提供的文档
NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
config.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
不相关,但是(可变!)
URLRequest
根本没有使用/需要。使用dataTaskWithURL
并传递URL。@vadian:你说得对。我拿出了一些东西让东西更可读。非常感谢。非常重要的知识。不过我不得不切换第2行和第3行。很好,这很有帮助。