在iOS上的AFNetworking中取消上传过程

时间:2013-06-26 08:20:48

标签: iphone ios objective-c afnetworking nsoperation

我从uiimagepickercontroller到服务器实现app upload image。但我想在上传过程中实现取消按钮取消上传。

在上传功能中:

[operation setCompletionBlock:^{
    ProgressView.hidden = YES;
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Uploading successfull." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [av show];
    [av release];
    overlayToolbar.userInteractionEnabled = YES;
    NSLog(@"response string: %@", operation.responseString); //Lets us know the result including failures
}];

NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];

并且buttoncancel:

[httpClient.operationQueue cancelAllOperations];

当我按下buttoncancel时,它不会停止上传过程,然后出现alertview“上传成功”。我不知道为什么不能停止但仍然会出现alertview。 alertview 你能救我吗?

1 个答案:

答案 0 :(得分:5)

您正在取消错误的操作队列。您要将操作添加到全新的NSOperationQueue,但是您在cancelAllOperations上呼叫httpClient.operationQueue

如果您在已添加操作的同一操作队列上取消上传,则应该有效。这是AFURLConnectionOperation.m取消时发生的情况:

- (void)cancel {
    [self.lock lock];
    if (![self isFinished] && ![self isCancelled]) {
        [self willChangeValueForKey:@"isCancelled"];
        _cancelled = YES;
        [super cancel];
        [self didChangeValueForKey:@"isCancelled"];

        // Cancel the connection on the thread it runs on to prevent race conditions
        [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
    }
    [self.lock unlock];
}

关于操作队列的更多背景知识:

cancelAllOperations通常会取消所有待处理的操作。如果某个操作已在进行中,则可以取消它正在执行的操作(AFNetworking正在处理此情况)。

  

此方法向当前的所有操作发送取消消息   队列。排队操作在开始执行之前被取消。如果   一个操作已经在执行,由该操作决定   认识到取消并停止它正在做什么。

来源:http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html#//apple_ref/occ/instm/NSOperationQueue/cancelAllOperations

这可能会对您有所帮助:http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues

此外,在AFNetworking的特殊情况下,这可能也很有趣:How to immediately force cancel an NSOperation with AFNetworking?