我的应用程序需要从网络上获取一些图片,但我希望用户能够取消这个下载(如果它没有连接,或者它太慢,或者w/e)。在任何情况下,应用程序界面都不应该被“冻结”。因此,我使用AFHTTPClient和enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock:方法下载:
NSMutableArray *operationsArray = [NSMutableArray array];
for (NSString *imageURL in imageURLArray) {
AFImageRequestOperation *getImageOperation =
[AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]]
imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
//
// Save image
//
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
if((error.domain == NSURLErrorDomain) && (error.code == NSURLErrorCancelled))
NSLog(@"Image request cancelled!");
else
NSLog(@"Image request error!");
}];
[operationsArray addObject:profileImageOperation];
}
//
// Lock user interface by pop-up dialog with process indicator and "Cancel download" button
//
[afhttpClient enqueueBatchOfHTTPRequestOperations:operationsArray
progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
//
// Handle process indicator
//
} completionBlock:^(NSArray *operations) {
//
// Remove blocking dialog, do next tasks
//
}];如果按下“取消下载”按钮:
- (void)cancelDownloadDialogButtonClicked {
[afhttpClient.operationQueue cancelAllOperations];
}我的问题是:
我不知道我应该在哪里检查操作错误和取消(在这种情况下,我想取消整个下载和删除UI阻塞对话框)。在我看来,最好的位置是在completionBlock: of enqueueBatchOfHTTPRequestOperations:中,因为它保证所有的操作都已经完成,并且我可以访问NSArray *operations,所以我可以检查它是错误还是取消,就像我在failure:中所做的那样。但是我发现在这种情况下甚至没有执行这个块(可能是因为isCancelled、isFinished、isExecuting属性机制)。
那么,如果用户按了“取消下载”按钮,我应该如何删除UI阻塞对话框并取消下载呢?
更新
不知道为什么,但是在本例中,Cancelling batch request in AFNetworking取消检查在completionBlock:中,这正是我要把它放在哪里的!但是在我的例子中,如果取消了任何操作,这个块就不会执行!也许我在配置AFHTTPClient时遗漏了什么?
发布于 2013-06-03 10:27:10
取消所有操作使用
[[client operationQueue] cancelAllOperations];删除UI阻塞对话框
你必须包括移除方言的代码
弄清楚
- (void)cancelDownloadDialogButtonClicked {
[afhttpClient.operationQueue cancelAllOperations];
//DO Remove the UI blocking mechanism here Eg.
[SVProgressHUD dismiss];
}https://stackoverflow.com/questions/16894610
复制相似问题