Waiting for completion block to complete in an AFNetworking request

Kamran picture Kamran · May 20, 2012 · Viewed 16.5k times · Source

I am making a JSON request with AFNetworking and then call [operation waitUntilFinished] to wait on the operation and the success or failure blocks. But, it seems to fall right though - in terms of the log messages, I get "0", "3", "1" instead of "0", "1", "3"

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://google.com"]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"query", @"q", nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:[url path] parameters:params];
NSLog(@"0");
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *innerRequest, NSHTTPURLResponse *response, id JSON) {
 NSLog(@"1");
 gotResponse = YES;
} failure:^(NSURLRequest *innerRequest, NSHTTPURLResponse *response, NSError *error, id JSON) {
  NSLog(@"2");
  gotResponse = YES;
}];
NSLog(@"Starting request");
[operation start];
[operation waitUntilFinished];
NSLog(@"3");

Answer

Kamran picture Kamran · May 20, 2012

This works by using AFNetworking to set up the requests, but making a synchronous call then handling the completion blocks manually. Very simple. AFNetworking doesn't seem to support this https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ, though the work around is simple enough.

#import "SimpleClient.h"

#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#import "AFJSONUtilities.h"

@implementation SimpleClient

+ (void) makeRequestTo:(NSString *) urlStr
        parameters:(NSDictionary *) params
        successCallback:(void (^)(id jsonResponse)) successCallback 
        errorCallback:(void (^)(NSError * error, NSString *errorMsg)) errorCallback {

   NSURLResponse *response = nil;
   NSError *error = nil;

   NSURL *url = [NSURL URLWithString:urlStr];

   AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

   httpClient.parameterEncoding = AFFormURLParameterEncoding;

   NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:[url path] parameters:params];
   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

   if(error) {
      errorCallback(error, nil);
   } else {
      id JSON = AFJSONDecode(data, &error);
      successCallback(JSON);
   }
}

@end