我正在为我的项目开发一个networkUtil,我需要一个获取url的方法,并使用NSURLSessionDataTask从该URL返回从该URL获得的JSON以从服务器获取JSON。方法如下:方法在完成处理程序之前返回
+ (NSDictionary*) getJsonDataFromURL:(NSString *)urlString{
__block NSDictionary* jsonResponse;
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", jsonResponse);
}];
[dataTask resume];
return jsonResponse;
}
的问题是,completionHandler我的方法内部和方法本身是在不同的线程,并在最后一行jsonResponse运行总是零
我该如何设置jsonResponse与返回的json从urlString?
什么是最佳实践这个问题?
这是因为你在做异步调用。有很多关于它的问题。 – Larme