Search code examples
iosobjective-cnetwork-programminghttp-postafhttpclient

iOS Emptying Queue of Requests


When you create/update/delete a record in my app it creates an OutgoingRequest in Core Data. Periodically, the app will get these requests in a queue, and push them all to the server. I do this using a AFHTTPClient post (seen below). The issue I am running into is that it pushes all of these requests up at one time, then the responses come back in no real order.

What I need to do is make these requests work 'synchronically' in that request B should not be posted until request A has finished (success or fail response). This is done in the background as well, and should not hang the UI.

for(OutgoingRequest *req in queue)
{
    NSURL *reqUrl = [NSURL URLWithString: globals.baseURL];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:reqUrl];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            req.url, @"viewName",
                            req.json, @"JSON",
                            req.dateAdded.description, @"dateTime",
                            nil];

    NSString *path = [NSString stringWithFormat:@"cache/update/?deviceUID=%@&token=%@", [MySingleton getMacAddress],  globals.token];

    [httpClient postPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

            //handle the repsonse

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

Is there any way to achieve this with my current setup? Or should I be using other means to POST to my server?

Thanks


Solution

  • Probably the best idea here is to use AFHTTPRequestOperation (or one of it subclasses) and create a dependencies between them: 2 op. depends on 1 op., 3 op. depends on 2 op. and so on...

    Please take a look to AFNetworking and NSOperation documentation (AFHTTPRequestOperation is a subclass of NSOperation).