AFNetworking 2:如何取消AFHTTPRequestOperationManager请求?

ozz*_*tto 37 afnetworking-2

我将我的网络功能迁移AFNetworking到了AFNetworking v2,而不是AFHttpClientAFHTTPRequestOperationManager用来支持iOS6.

我的问题是,虽然AFHttpClient有使用.取消待处理请求的功能

- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
Run Code Online (Sandbox Code Playgroud)

方法,在AFHTTPRequestOperationManager没有这种明显的方法.

我到目前为止所做的是AFHTTPRequestOperationManager继承和声明一个iVar

AFHTTPRequestOperation *_currentRequest;
Run Code Online (Sandbox Code Playgroud)

当我提出请求时,代码就是这样的

- (void)GetSomething:(NSInteger)ID success:(void (^)(MyResponse *))success failure:(void (^)(NSError *))failure
{
    _currentRequest = [self GET:@"api/something" parameters:@{@"ID": [NSNumber numberWithInteger:ID]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyResponse *response = [MyResponse responseFromDictionary:responseObject];
        success(response);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);

    }];
}
Run Code Online (Sandbox Code Playgroud)

我有一个

- (void)cancelCurrentRequest;
Run Code Online (Sandbox Code Playgroud)

所有这些的方法都是

- (void)cancelCurrentRequest
{
    if(_currentRequest) {
        [_currentRequest cancel]; _currentRequest = nil;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我不认为这是一个好的做法,当调用该方法时,我得到了 (NSURLErrorDomain error -999.)这就是为什么我需要一些关于正确完成这个的建议.

先感谢您.

Gar*_*Lyn 80

[manager.operationQueue cancelAllOperations];
Run Code Online (Sandbox Code Playgroud)

  • 谢谢答案.我已经注意到了,但如果您想要取消特定的GET/POST请求怎么办? (3认同)
  • 如果你查看cancelAllHTTPOperationsWithMethod:path的实现,你会发现如何做到这一点.它只是迭代operationQueue中的所有操作,找到与方法和路径匹配的操作并取消它们.他们在v2中删除它们的原因我猜它们认为没有必要取消特定的操作? (3认同)