0

我正在使用 Http POST 请求和 NSURLRequest 解析一些 JSON 数据。但是,当我得到 sendAsynchronousRequest 下的值时,我无法在该请求之外使用这些值。请看下面的例子:

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         NSError *parseError = nil;
         dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }];

我的查询是如何在需要的地方使用字典值?谢谢

4

1 回答 1

2

您可以通过多种方式做到这一点。一种方法是声明一个属性并在块内使用它。

当您进行异步调用时,最好有自己的自定义块来响应这些调用。

先声明一个完成块:

 typedef void (^ ResponseBlock)(BOOL success, id response);

并声明一个将此块用作参数的方法:

 - (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion;

并在此方法中包含您的异步调用:

- (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion{

 [NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     NSError *parseError = nil;
     dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
     NSLog(@"Server Response (we want to see a 200 return code) %@",response);
     NSLog(@"dictionary %@",dictionary);
     completion(YES,response); //Once the async call is finished, send the response through the completion block
 }];

}

你可以在任何你想要的地方调用这个方法。

 [classInWhichMethodDeclared processMyAsynRequestWithCompletion:^(BOOL success, id response) {
      //you will receive the async call response here once it is finished.
         NSDictionary *dic = (NSDictionary *)response;
       //you can also use the property declared here
           _dic = (NSDictionary *)response; //Here dic must be declared strong
 }];
于 2016-11-15T20:18:24.457 回答