我将网络功能从AFNetworking
迁移到AFNetworking v2
而不是AFHttpClient
我正在使用AFHTTPRequestOperationManager
来支持iOS6。
我的问题是,在AFHttpClient
中,有使用
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
方法,在AFHTTPRequestOperationManager
中没有这样明显的方法。
我到目前为止所做的是继承AFHTTPRequestOperationManager
并声明一个iVar
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.)
,这就是为什么我需要一些建议才能正确完成。
提前谢谢。
答案 0 :(得分:80)
[manager.operationQueue cancelAllOperations];
答案 1 :(得分:2)
您不必继承AFHTTPRequestOperationManager
,因为当您发送请求时,AFHTTPRequestOperation
会从
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
只需将其保存在某处或制作静态,然后在需要取消请求时执行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;
}