Reputation: 285
I have a view controller which will make a server request. I have put all server request handlers in a single class. So in the view controller, just use [Apihandler getlist] to get list for example.
In class Apihandler, I used block in
[_request setCompletionBlock:^{}]
to get server response (JSON object).
If JSON object contains a key/value named "error", I will take it as failure though it is complete to ASIHttpRequest itself. Otherwise, it is success.
The question is: how do I get the return value of above completion block? I checked ASI document, ASIBasicBlock is void return type.
Upvotes: 0
Views: 251
Reputation: 551
I did this with a delegate. So I have code that looks like this:
[request setCompletionBlock:^{
NSLog(@"Data retrieved");
NSData *data = [request responseData];
NSLog(@"Status Code: %d", [request responseStatusCode]);
dispatch_async(backgroundQueue, ^(void){
[self processData:data];
});
}];
Which basically says when this completion block runs, call the processData message in the background. In the processData message I make use a delegate to return data to my main UI thread. That message looks like this:
- (void)processData:(NSData *)data {
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
dispatch_async(dispatch_get_main_queue(), ^(void){
[self.delegate requestDataReady:json];
});
}
I hope that helps.
UPDATE:
Of course you don't have to run the process method in a background thread. You could just as easily call [self processData:data] within the block or even place the code from processData inside of the block.
Upvotes: 2