AFNetworking 2:如何取消AFHTTPRequestOperationManager请求?
我将我的networkingfunction从AFNetworking
迁移到AFNetworking v2
,而不是AFHttpClient
我使用AFHTTPRequestOperationManager
来支持iOS6。
我的问题是,虽然在AFHttpClient
有function取消一个未决的请求使用
- (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.)
这就是为什么我需要一些正确的做法的build议。
先谢谢你。
[manager.operationQueue cancelAllOperations];
您不必子类化AFHTTPRequestOperationManager
,因为当您发送请求时, AFHTTPRequestOperation
从
- (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
只需将其保存在某个地方或使其成为静态,然后在需要取消请求时执行取消。
例:
- (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; }