我正在开发一个与Google Data API接口的项目。我有几个独立的HTTP GET和HTTP POST类用于与Google交互,它们都是异步的。我担心用户可能会在操作完成之前触摸主页按钮,从而导致服务器/客户端同步奇偶校验的分歧。我不了解后台任务API,因为我似乎必须在后台块中封装每个GET或POST请求,并且每个块都必须从我的Application Delegate中调用。这是真的?如果是这样,那么尝试重写我现有的许多上传和下载逻辑会引起很大的麻烦。
感谢您的投入! =)
答案 0 :(得分:2)
我建议使用NSOperationQueue
排队所有HTTP请求,然后只使用一个后台任务。您可以指定允许与setMaxConcurrentOperationCount
并行运行的操作数。
使用ASIHTTPRequest框架时,ASINetworkQueue是NSOperationQueue
的子类,这非常简单。
在后台持续下载也很容易:http://allseeing-i.com/ASIHTTPRequest/How-to-use#background_downloads_ios。
答案 1 :(得分:2)
有一个名为ASIHTTPRequest的第三方库使这个过程变得非常简单。假设您使用的是iOS 4,您只需创建一个ASIHTTPRequest并将参数shouldContinueWhenAppEntersBackground设置为YES,它将为您封装所有后台逻辑,并仅显示块回调。
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];