Iphone 在后台使用NSOperationQueue按时间顺序执行AFHTTPClient请求
我有一个HTTPClient请求,如下所示:Iphone 在后台使用NSOperationQueue按时间顺序执行AFHTTPClient请求,iphone,ios,nsoperationqueue,afhttpclient,Iphone,Ios,Nsoperationqueue,Afhttpclient,我有一个HTTPClient请求,如下所示: NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:urlStringMain]]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:urlStringMain]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
//parameters
nil];
[self beginBackgroundUpdateTask];
[httpClient postPath:postPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//id results = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONWritingPrettyPrinted error:nil];
//completion code
[self endBackgroundUpdateTask];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure code
}];
[httpClient release];
后台任务在以下位置执行:
- (void) beginBackgroundUpdateTask{
[operationQueue addOperationWithBlock:^{
NSLog(@"started upload process as a background job");
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}];
}
结果是:
- (void) endBackgroundUpdateTask{
NSLog(@"complete upload process as a background job");
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
其中self.backgroundUpdateTask是UIBackgroundTaskIdentifier
对象,operationQueue是NSOperationQueue
(公共成员)的对象,在viewDidLoad
中初始化:
operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
现在我想做的是,在后台按时间顺序执行这些请求,这样从viewController
推/弹出不会影响请求。如果应用程序进入后台,它也不会受到影响。有时我发布文本,有时我发布图像。现在,上传图像比上传文本需要更长的时间,所以如果后续请求文本和图像,则首先发布文本,然后发布图像。这打破了任务的时间顺序,因此我想使用NSOperationQueue
。但作为一个新的操作队列,我似乎无法让它工作。年表仍然没有得到尊重。如何以我想要的方式执行任务
另外,正如您在代码中所看到的,我在httpClient
请求的完成块和beginBackgroundUpdateTask方法中都添加了[self-endBackgroundUpdateTask]
。现在我明白这是不好的。究竟应该在哪里调用endBackgroundUpdateTask方法
谢谢。如果您要求,
HTTPClient
可以为您处理后台任务,只需设置适当的标志(您需要创建操作并调用setShouldeExecuteAsbackgroundTaskWithExpirationHandler:
)
与其改变上传的操作方式,不如保持简单。发送上载日期,并使用该日期在服务器上维护您的订单信息
如果确实必须串行执行操作,则可以从客户端获取
operationQueue
,并将其设置为一次仅执行一个操作
在这两种情况下,您都不需要创建自己的操作队列。这没有帮助。服务器使用自己的时钟为所有帖子分配时间戳。