objective-cjsonsendasynchronousrequest

How to use the values out of sendAsynchronousRequest?


I am parsing some JSON data using Http POST request and NSURLRequest. But when I have got the values under sendAsynchronousRequest I cannot use those out side of that request. Please see the example bellow:

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

My query is how can I use the dictionary value where I need it? Thanks


Solution

  • You can do it in many ways. One way is to declare a property and use it inside the block.

    As you are making an asynchrounous call, it is better to have your own custom blocks to respond to those calls.

    Declare a completion block first:

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

    and declare a method that uses this block as a param:

     - (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion;
    

    and include your async call in this method:

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

    You can call this method anywhere you want.

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