iOS Task Completion pattern for asynchronous downloads and uploads
I'm working on a project that interfaces with Google Data APIs. I have several independent classes for HTTP GET and HTTP POST for interacting with Google, and they are all asynchronous. I'm concerned that a user might touch the home button before operations are finished, thus causing rifts in server/client sync parity. I don't understand the background task API, as it se开发者_JS百科ems that I have to encapsulate every single GET or POST request in a background block, and each block has to be called from my Application Delegate. Is this true? If so, it would cause a major headache to try to rewrite a lot of my existing upload and download logic.
Thanks for your input! =)
I recommend to queue all the HTTP Requests using a NSOperationQueue
and then only use one background task. You can specify how many operations are allowed to run in parallel with setMaxConcurrentOperationCount
.
When you use ASIHTTPRequest framework, this is very easy with ASINetworkQueue, a subclass of NSOperationQueue
.
Continuing downloads in the background is easy too: http://allseeing-i.com/ASIHTTPRequest/How-to-use#background_downloads_ios.
There is a 3rd party library called ASIHTTPRequest that makes this process very simple. Assuming that you are using iOS 4 you can simply create an ASIHTTPRequest and set the parameter shouldContinueWhenAppEntersBackground to YES and it will encapsulate all of the background logic for you and only expose the block callback.
NSURL *url = [NSURL URLWithString:@"http://example.com/path/to/resource"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.shouldContinueWhenAppEntersBackground = YES;
[request setCompletionBlock:^
{
NSString *responseString = [request responseString];
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"Error = %@",error);
}];
[request startAsynchronous];
精彩评论