如何使用 sendAsynchronousRequest 中的值?

How to use the values out of sendAsynchronousRequest?

我正在使用 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);
     }];

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

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

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

首先声明一个完成块:

 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
 }];