从NSURLResponse完成块中获取数据

看起来我还没有完全得到块的概念…

在我的代码中,我必须从asychronous block获取JSON数据,并从“ outer ”方法返回。 我searchvariable with __block ,发现如果variable with __block定义一个variable with __block这个variables的variables被扩展到这个block

但由于某种原因返回的JSON对象是零。我想知道为什么?

 - (NSMutableDictionary *)executeRequestUrlString:(NSString *)urlString { __block NSMutableDictionary *json = nil; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPShouldHandleCookies:YES]; [request setHTTPMethod:@"GET"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"]; NSString *cookieString = [self.userDefaults objectForKey:SAVED_COOKIE]; [request addValue:cookieString forHTTPHeaderField:@"Cookie"]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); NSError *error1; NSMutableDictionary * innerJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1]; json = innerJson; }]; return json; } 

首先,回答你的问题:

但由于某种原因返回的json对象是nil 。 我想知道为什么?

您返回的variables尚未在您返回时设置。 在sendAsynchronousRequest:queue:completionHandler:方法已经返回之后,您不能立即收获结果:调用必须在callback块并设置jsonvariables之前完成往返。

现在快速记下如何处理它:您的方法正在尝试将asynchronous调用转换为同步调用。 如果可以,尽量保持asynchronous。 不要期望返回一个NSMutableDictionary*的方法,而是创build一个方法,它接收一个自己的块,并在sendAsynchronousRequest:方法完成时将字典传递给该块:

 - (void)executeRequestUrlString:(NSString *)urlString withBlock:(void (^)(NSDictionary *jsonData))block { // Prepare for the call ... // Make the call [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); NSError *error1; NSMutableDictionary * innerJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1 ]; block(innerJson); // Call back the block passed into your method }]; } 

当你调用sendAsynchronousRequest:queue:completionHandler: ,你已经请求了一个asynchronous请求。 所以它将请求和块排队,并立即返回。 在将来的某个时刻,请求会被执行,并在此之后的某个点运行完成块。 但到那个时候, return json已经运行很久了。

如果您希望能够同步返回数据,则必须发出同步请求。 这将挂起这个线程,直到它完成,所以它不能是主线程。

使用以下代码转换来自服务器的数据时检查string:

  NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); 

如果string是正确的JSON格式,那么你的JSON对象将是正确的。

希望这个肝!