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?