This post, I will show how you can use AFNetworking to queue multiple HTTP operations. They could be running concurrently, or have dependencies.
Adding dependencies to HTTP operations is especially useful. For example, you can make sure that you fetch a list of resources, then fetch image1, then image2, …
Adding operations to a queue is rather simple.
You will be using NSOperationQueue, which is part of Apple’s Foundation framework.
You will be adding NSOperation to the queue. Not surprisingly, classes such as AFHTTPRequestOperation subclass NSOperation.
Adding an operation to a queue
12345678910111213141516
// Create a http operationNSURL*url=[NSURLURLWithString:@"http://samwize.com/api/cars/"];NSURLRequest*request=[NSURLRequestrequestWithURL:url];AFHTTPRequestOperation*operation=[[AFHTTPRequestOperationalloc]initWithRequest:request];[httpClientregisterHTTPOperationClass:[AFHTTPRequestOperationclass]];[operationsetCompletionBlockWithSuccess:^(AFHTTPRequestOperation*operation,idresponseObject){// Print the response body in textNSLog(@"Response: %@",[[NSStringalloc]initWithData:responseObjectencoding:NSUTF8StringEncoding]);}failure:^(AFHTTPRequestOperation*operation,NSError*error){NSLog(@"Error: %@",error);}];// Add the operation to a queue// It will start once addedNSOperationQueue*operationQueue=[[NSOperationQueuealloc]init];[operationQueueaddOperation:operation];
As you can see, it is just 2 more lines of code.
Adding multiple operations and run them concurrently
1234
NSOperationQueue*operationQueue=[[NSOperationQueuealloc]init];// Set the max number of concurrent operations (threads)[operationQueuesetMaxConcurrentOperationCount:3];[operationQueueaddOperations:@[operation1,operation2,operation3]waitUntilFinished:NO];
Adding Dependencies
Let’s say we have 2 operations, and we want operation2 to start only after operation1 has finish.
1234
NSOperationQueue*operationQueue=[[NSOperationQueuealloc]init];// Make operation2 depend on operation1[operation2addDependency:operation1];[operationQueueaddOperations:@[operation1,operation2,operation3]waitUntilFinished:NO];