0

I am using NSURLRequest and NSOperationQueue to perform a web service call. The problem for me is that code after the block is executing before the code in the block. I have a method -(bool)getLiveData where the web service call is made and the reponse is converted into a NSDictionary using the jsonserialization class. If the conversion is succesful the method returns true and then the data gets passed to table view. If the data is null then false is returned and UIAlertView is shown.

Here is code in method:

-(bool)getLiveData{

NSURL *jsonURL = [NSURL URLWithString:[self urlEncodeValue:s1]]; //s1 is NSString 
NSURLRequest *request = [NSURLRequest requestWithURL:jsonURL];


[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response,
                                           NSData *data, NSError *connectionError)
 {
     if(data.length > 0 && connectionError == nil)
     {
       //use json serilization to create nsdictionary object called jsonDict then use its objectForKey to access values. 

      }

}];



if([[[[[self.jsonDict valueForKey:@"response"] valueForKey:@"groups"] objectAtIndex:0] valueForKey:@"items"] count] > 0)
    return TRUE;
else
    return FALSE;
}

So the first time I make web service call the UIAlertView is shown saying no data has been found, even though there actually is. That is because in the last if-else statement the else is executed and false is being returned. Then the second web service call shows the data of the first service call unless I reload it. The third service call shows data of second call...and so on. I looked it up online and found out that this is happening because the block is not done executing and the code after it executes before, as soon as the block executes the right data is shown. Is there any other way I approach this?

Harshil.Chokshi
  • 671
  • 15
  • 26
  • Okay I looked at the duplicate. But i am confused with the block in a block concept. Can someone please tell me how i would implement it with my code. – Harshil.Chokshi Apr 25 '16 at 18:52
  • Instead of your getLiveData method returning a boolean value, make it a void method that takes a callback block as a parameter. The callback block should take a single bool parameter. When you call getLiveData, instead of doing something with the return value, take all the rest of the code in that calling method and put it into a block. Pass that block to getLiveData. In getLiveData's completion handler block, call your custom callback block, and pass it the value you would have returned. This effectively defers running the code in the calling method until you've received a response. – dgatwood May 02 '16 at 05:02

0 Answers0