2013-11-22 84 views
36

我将我的网络功能从AFNetworking迁移到AFNetworking v2,而不是AFHttpClient我使用AFHTTPRequestOperationManager来支持iOS6。AFNetworking 2:如何取消AFHTTPRequestOperationManager请求?

我的问题是,虽然在AFHttpClient有功能使用

- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path; 

方法,在AFHTTPRequestOperationManager没有这样明显的方法取消挂起的请求。

我所做的到现在是继承AFHTTPRequestOperationManager并宣布伊娃

AFHTTPRequestOperation *_currentRequest; 

当我提出请求的代码是一样的东西

- (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); 

    }]; 
} 

,我有一个

- (void)cancelCurrentRequest; 

所有的方法是

- (void)cancelCurrentRequest 
{ 
    if(_currentRequest) { 
     [_currentRequest cancel]; _currentRequest = nil; 
    } 
} 

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

预先感谢您。

回答

79
[manager.operationQueue cancelAllOperations]; 
+3

Thx的答案。我注意到了,但是如果你想取消一个特定的GET/POST请求呢? – ozzotto

+3

如果你看看cancelAllHTTPOperationsWithMethod:路径的实现,你会发现如何去做。它只是迭代operationQueue中的所有操作以找到与方法和路径匹配并取消它们的操作。他们在v2中删除它们的原因我猜他们认为没有必要取消特定的操作? –

+0

这就是我最终做的。在我的AFHTTPRequestOperationManager子类中实现cancelAllHTTPOperationsWithMethod:路径。 Thx队友。 – ozzotto

2

您不必继承AFHTTPRequestOperationManager,因为当你发送请求,从

- (AFHTTPRequestOperation *)GET:(NSString *)URLString 
        parameters:(id)parameters 
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 

AFHTTPRequestOperation回报只是保存在某个地方,或使静态的,然后执行cancel时要求必须是取消。

实施例:

- (void)sendRequestToDoSomething 
{ 
    static AFHTTPRequestOperation *operation; 
    if(operation) //cancel operation if it is running 
     [operation cancel]; 
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
    //configure manager here.... 

operation = [manager GET:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    //do something here with the response 
    operation = nil; 
} failure:^(AFHTTPRequestOperation *op, NSError *error) { 
{ 
    //handle error 
    operation = nil; 
}