我用get函数作为例子来说明怎么取消当前的网络请求(post等操作一样可以这么做,不是大同小异,是一样)
这里是我的get函数:
+ (AFHTTPRequestOperation*)getJSONDataWithUrlPath:(NSString *)url_path parameters:(id)parameters success:(void (^)(id json))success fail:(void (^)())fail
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString* urlStr = [NSString stringWithFormat:@"%@%@", IP_STR, url_path];
__block AFHTTPRequestOperation* http_operation;
AFHTTPRequestOperation* operation =
[manager GET:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
http_operation = operation;
success(responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败,错误信息:error==%@", error);
if (fail) {
http_operation = operation;
fail();
}
}];
return operation;
}
请求的时候将当前的AFHTTPRequestOperation 作为为返回值,返回给调用者保存起来,然后在任何你想要取消这一个请求的时候,调用cancel,就可以了。
NSDictionary* paraDic = [NSDictionary dictionaryWithObjectsAndKeys:email,@"user.email",psw, @"user.password",nil];
self.m_currentHTTPRequestOp = [KKHttp getJSONDataWithUrlPath:@"用户登录" parameters:paraDic success:^(id json)
{
NSLog(@"登录成功");
}fail:
^{
NSLog(@"登录失败");
}];
//设置五秒的等待时间,超过就算请求失败,手动取消这一次请求
[NSTimer scheduledTimerWithTimeInterval:5.f target:self selector:@selector(requestTimeOut) userInfo:nil repeats:NO];
-(void)requestTimeOut
{
[self.m_currentHTTPRequestOp cancel];
}