【问题标题】:AFHTTPRequestOperation Cancel RequestAFHTTPRequestOperation 取消请求
【发布时间】:2013-12-17 15:49:28
【问题描述】:

有没有办法取消 AFHTTPRequestOperation?例如,我正在使用它来下载 PLIST。所以我打算有一个按钮来取消下载或任务。 有什么办法吗?

更新:

operationQueue = [NSOperationQueue new];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFPropertyListResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id propertyList) {

    NSLog(@"DONE");        

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"%@", error);

}
 ];

 [operationQueue addOperation:operation];

所以我已将“操作”放入“操作队列”,并且可以通过以下方式停止操作:

[operationQueue cancelAllOperations];

这只是队列中的一项操作。如果有多个,有没有办法显式停止操作?我猜控制台中出现以下错误 - 如果队列被取消是否正常?

Error Domain=NSURLErrorDomain Code=-999 "操作无法完成。

【问题讨论】:

    标签: ios afnetworking-2


    【解决方案1】:

    你可以使用:

    [operation cancel];
    

    这是一个由 AFNetworking 实现的 NSOperation 方法。

    【讨论】:

    • 我如何从另一个(void)调用它,因为操作只在调用连接的这个函数中知道。
    • 您有几个选择。例如,您可以将operation 保存为弱@property,或者您可以将其添加到NSOperationQueue 而不是对其调用start,然后稍后从同一个队列中找到它。这是 NSOperation 的一个很好的概述:nshipster.com/nsoperation
    • 感谢 NSOperation 的提示。已经更新了我上面的代码。我认为如果取消操作,控制台日志中的错误是正常的吗?
    • 是的,错误 -999 是预期行为。如果您最终有多个操作,您可以查看operationQueue.operations 数组,然后搜索您想要的那个。例如,您可以查看 operation.request.URL.path 以查看它是否包含您要取消的 URL。
    • @Ruddy 不要记录错误如果error.code == kCFURLErrorCancelled && [error.domain isEqualToString:NSURLErrorDomain]
    【解决方案2】:

    您可以使用它来取消所有操作:

    [[httpClient operationQueue] cancelAllOperations];
    

    【讨论】:

    • httpClient到底是什么?对我来说,这是一个未声明的标识符。谢谢
    • httpClient 是您用于创建连接的AFHTTPClient 的实例。无论如何,我刚刚意识到亚伦的答案更适合你的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 2012-01-18
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多