AFNetworking并发请求管理
GCD并发多个请求
有时候需要某些请求都结束了再进行某个操作, 而AFNetworking并不支持网络管理, 特地网上找了一下,发现网上的要不过于复杂,要不可能就存在错误,希望今天能给大家带来一种新的思路。
直接上代码:
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
// manager.completionGroup = group;
// manager.completionQueue = queue;
dispatch_group_enter(group);
[manager GET:@"https://www.yiketianqi.com/free/day" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[NSThread sleepForTimeInterval:2];
dispatch_group_leave(group);
NSLog(@"01-1");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[NSThread sleepForTimeInterval:2];
NSLog(@"01");
}];
AFHTTPSessionManager *manager01 = [[AFHTTPSessionManager alloc] init];
// manager01.completionGroup = group;
// manager01.completionQueue = queue;
dispatch_group_enter(group);
[manager01 GET:@"https://www.yiketianqi.com/free/day" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
dispatch_group_leave(group);
NSLog(@"02-2");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
dispatch_group_leave(group);
}];
AFHTTPSessionManager *manager02 = [[AFHTTPSessionManager alloc] init];
// manager01.completionGroup = group;
// manager01.completionQueue = queue;
dispatch_group_enter(group);
[manager02 GET:@"https://www.yiketianqi.com/free/day" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
dispatch_group_leave(group);
NSLog(@"03-3");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
dispatch_group_leave(group);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"finish");
});
刚开始发现AFN自带一个completionGroup&completionQueue
想通过这两个加上dispatch_group_notify
来实现异步请求管理,但是发现怎么都是先执行了finish
, 调试后发现
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
...
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
}
...
}
dispatch_group_async
的执行时机晚于dispatch_group_notify
的调用时机, 所以dispatch_group_notify
根本没起到作用,所以采用了第二种方案
- 异步请求调用前调用:
dispatch_group_enter(group)
- 请求结束后调用:
dispatch_group_leave(group)
最终程序如期运行,不过这种做法可能会block主线程,导致卡顿,可以套一个线程,把整个逻辑放到子线程中。
PS: 这种需求较少,简单情况下可以如此操作, 如果这种情况较多, 建议使用[YTKNetwork](https://github.com/yuantiku/YTKNetwork)
祝大家好运~
网友评论