拿到 NSOperation取消单个网络请求,operation 直接取消:[operation cancel];
用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; }
取消所有的 operation --
[[MGJRequestManager sharedInstance] cancelAllRequest];
- (void)cancelAllRequest
{
[self.requestManager.operationQueue cancelAllOperations];
}
取消某个URL的请求
- (void)cancelHTTPOperationsWithMethod:(NSString *)method url:(NSString *)url
{
NSError *error;
NSString *pathToBeMatched = [[[self.requestManager.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:url] absoluteString] parameters:nil error:&error] URL] path];
for (NSOperation *operation in [self.requestManager.operationQueue operations]) {
if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
continue;
}
BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]];
BOOL hasMatchingPath = [[[[(AFHTTPRequestOperation *)operation request] URL] path] isEqual:pathToBeMatched];
if (hasMatchingMethod && hasMatchingPath) {
[operation cancel];
}
}
}
网友评论
NSURLSessionDataTask *task = [manager GET:@"url地址"parameters:@"入参"progress:^(NSProgress *_Nonnull downloadProgress) {
//数据请求进度
} success:^(NSURLSessionDataTask *_Nonnull task,id _Nullable responseObject) {
//请求成功
} failure:^(NSURLSessionDataTask *_Nullable task,NSError *_Nonnull error) {
//请求失败
}];
//取消单个网络请求
[task cancel];
//取消所有的网络请求
[manager.operationQueue cancelAllOperations];