Charlie Wu
Charlie Wu

Reputation: 7757

AFHTTPRequestOperation synchronous request

I have a situation where I need to make multiple request to a server where subsequent request will depend on previous request

1) request 1
2) process data
3) request 2 based on data in step 2
4) process data

what's the best way to approach this for AFNetworking 2

Upvotes: 0

Views: 1317

Answers (2)

Charlie Wu
Charlie Wu

Reputation: 7757

I had a play around and the ended up implement my own completion block and failure block so they can be executed on the some thread as the request operation by adding a category to the AFHTTPRequestOperation class

- (void)startAndWaitWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [self start];
    [super waitUntilFinished];

    id responseObject = self.responseObject; // need this line for AFNetworking to create error;

    if (self.error) {
        if (failure) failure(self, self.error);
    } else {
        if (success) success(self, responseObject);
    }
}

The operation will start then block the thread till the operation is completed. Then depend on success or failure, call the corresponding block before finish the operation.

This way i can chain multiple request operation one after another and the completion block will have the processed data from the previous request completion block

Upvotes: 0

Dave Kasper
Dave Kasper

Reputation: 1389

Call the second request in the completion handler of the first request. Here is some example code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON Response 1: %@", responseObject);

    // Process data here, and use it to set parameters or change the url for request2 below

    [manager GET:@"http://example.com/request2.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(@"JSON Response 2: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"Error 2: %@", error);
    }];
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error 1: %@", error);
}];

Upvotes: 1

Related Questions