【问题标题】:Cancel upload process in AFNetworking on iOS在 iOS 上取消 AFNetworking 中的上传过程
【发布时间】:2013-06-26 08:20:48
【问题描述】:

我实现了从 uiimagepickercontroller 到服务器的应用程序上传图像。但我想在上传过程中实现取消按钮来取消上传。

在上传功能中:

[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];

还有按钮取消:

[httpClient.operationQueue cancelAllOperations];

当我按下按钮取消时,它没有停止上传过程,然后出现alertview“上传成功”。我不知道为什么不能停止但仍然出现alertview。 警报视图 你能帮帮我吗?

【问题讨论】:

  • 当我按下按钮取消时它不起作用。什么不起作用?有日志吗?
  • 定义不工作。如您所知,该操作可能在分配给该按钮的操作触发之前完成。
  • 无法停止上传过程。@Rob

标签: iphone ios objective-c afnetworking nsoperation


【解决方案1】:

您取消了错误的操作队列。您正在将操作添加到一个全新的NSOperationQueue,但您在httpClient.operationQueue 上调用cancelAllOperations

如果您在已添加操作的同一操作队列上取消上传,它应该可以工作。这是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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2015-07-24
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多