如何使用sendAsynchronousRequest中的值?

时间:2016-11-15 20:03:06

标签: objective-c json 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);
     }];

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

1 个答案:

答案 0 :(得分: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
 }];