iphone - 在后台使用 NSOperationQueue 按时间顺序执行 AFHTTPClient 请求

标签 iphone ios nsoperationqueue afhttpclient

我有一个 HTTPClient 请求如下:

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(公共(public)成员)的一个对象,在viewDidLoad中初始化:

operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];

现在我想做的是,在后台按时间顺序执行这些请求,这样从 viewController 推送/弹出不会影响请求。如果应用程序进入后台,它也不应该受到影响。有时我发文字,有时我发图片。现在,图片比文本需要更长的时间上传,因此如果后续请求文本和图像,则先发布文本,然后再发布图像。这打破了任务的时间顺序,因此我想使用 NSOperationQueue。但是作为操作队列的新手,我似乎无法让它工作。年表仍然没有得到尊重。我如何以我想要的方式执行任务。

附言。另外,正如您在代码中看到的那样,我在 httpClient 请求的完成 block 和 beginBackgroundUpdateTask 方法中都添加了 [self endBackgroundUpdateTask]。现在我明白这不好。到底应该在哪里调用 endBackgroundUpdateTask 方法?

谢谢。

最佳答案

如果您要求,HTTPClient 可以为您处理后台任务,只需设置适当的标志(您需要创建操作并调用 setShouldExecuteAsBackgroundTaskWithExpirationHandler:)。

与其改变上传的操作方式,不如保持简单。发送上传日期并使用该日期在服务器上维护您的订单信息。


如果你真的必须连续执行你的操作,那么你可以从客户端获取 operationQueue 并将其设置为一次只执行一个操作。

无论哪种情况,您都不需要创建自己的操作队列。

关于iphone - 在后台使用 NSOperationQueue 按时间顺序执行 AFHTTPClient 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195830/

相关文章:

ios - 如何在纵向模式下锁定 viewController

objective-c - 如何停止当前的 NSOperation?

iphone - PerformSelectorOnMainThread 结果为 "unrecognized selector sent to instance"

iphone - 排除 UISpec 中的代码

iphone - 将具有大量子节点的 XML 解析为 UITableView

iphone - 使用非静态名称(FMDB)将数据插入数据库表

ios - 无法通过按住 Ctrl 并从元素中拖动来创建新操作

cocoa - NSOperation 等待异步 block 执行

iphone - 帮我象征崩溃

ios - 如何在按住手指时通过预览当前项目来模仿 iOS 键盘行为?