我正在使用 AFNetworking 框架。所以我创建了 AFHTTPClient 的子类:
+ (MyNetClient *)sharedClient
{
static MyNetClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:BASE_API_URL]];
});
return _sharedClient;
}
并添加了一些从服务器下载 JSON 的方法。
所以在我看来,我开始在 viewWillAppear 中下载,如下所示:
[[MyNetClient sharedClient] getArrOfDataWithName:name
block:^(NSArray *arr) {
}];
在哪里:
- (void)getArrOfDataWithName:(NSString *)name block:^(NSArray *arr)block
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *params = [NSMutableDictionary
dictionaryWithObjectsAndKeys:name,@"name",nil];
[self getPath:[self urlToService:@"data/get.json"] parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"result operation%@",operation);
BOOL res = [operation isCancelled];
if (!res)
{
dispatch_async(dispatch_get_main_queue(), ^{
block(responseObject);
});
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
block(nil);
});
}];
});
}
这需要更多时间,用户可以按回,所以我在 viewDidDisappear 中取消下载:
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[[LRLoopNetClient sharedClient] operationQueue] cancelAllOperations];
}
但下载操作并未取消。我在 getArrOfDataWithName 中添加了断点:
NSLog(@"result operation%@",operation);
BOOL res = [operation isCancelled];
res = NO 并且在我离开视图后调用它。我检查了:
NSInteger count = [[[LRLoopNetClient sharedClient] operationQueue] operationCount];
NSLog(@"number operations: %i",count);
在 viewDidDisappear 号码操作:0 请帮我取消下载。