我正在使用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 请帮我取消下载。