信号量实现AFNetworking网络请求顺序执行

应用场景

在一个页面,需要请求两个接口的数据,合并两个接口的数据,排序,然后显示到页面上。这个时候需要顺序执行两个网络请求,然后再处理数据刷新页面。
(因为实践发现,单纯使用GCD的group,如果在每个异步线程dispatch_group_async中,不执行网络请求还好,可以按照异步执行完后再汇总到dispatch_group_notify中。如果是网络请求,那就不行了,dispatch_group_notify执行完,估计网络请求才执行到。原因是AFNetworking网络请求也是一个子线程,嵌套多一层就会出问题。)

步骤

创建一个信号量,作为全局变量。
并初始化,信号量为0

dispatch_semaphore_t semaphore;
semaphore = dispatch_semaphore_create(0);

创建一个dispatch_group_t,开启两个组异步线程(dispatch_group_async),分别执行两个网络请求。
一个组通知线程(dispatch_group_notify),用于接收前面两个线程的结果。

dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_async(group, queue, ^{
        [weakSelf loadRelationDetail];//请求1
    });
    dispatch_group_async(group, queue, ^{
        [weakSelf loadRelationReward];//请求2
    });
    dispatch_group_notify(group, queue, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        //合并(此处是数据处理,你可根据具体业务需求进行处理)
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObjectsFromArray:weakSelf.arr1];
        [arr addObjectsFromArray:weakSelf.arr2];
        //排序
        if (arr.count > 1) {
            weakSelf.sumArr = [arr sortedArrayUsingComparator:^NSComparisonResult(ZHShareItem *obj1, ZHShareItem *obj2) {
                return [obj1.createTime compare:obj2.createTime];
            }];
        }else{
            weakSelf.sumArr = arr;
        }
        //有数据刷新
        if (weakSelf.sumArr.count > 0) {
            //在主线程刷新页面
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf initTableView];
            });
        }
    });

下面是我的两个请求:

请求1:

-(void)loadRelationDetail{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"uid"] = self.userInfo[@"UID"];
    params[@"session_id"] = self.userInfo[@"session_id"];
    params[@"token"] = [ZHHttpTools calToken:params];
    
    __weak typeof(self)weakSelf = self;
    [[ZHHttpTools share]POST:RelationDetail parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *code = [ZHHttpTools invokeCode:responseObject];
        NSString *message = [ZHHttpTools invokeMessage:responseObject];
        if ([code isEqualToString:@"200"]) {
            
            weakSelf.arr1 = [ZHShareItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"relation"]];
 
        }else{
            ZYLog(@"%@",message);
        }
       
        //注意这里,failure中也得添加一样的,用于标注信号量
        dispatch_semaphore_signal(semaphore);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ZYLog(@"%@",error);
        dispatch_semaphore_signal(semaphore);
    }];
}

请求2:

-(void)loadRelationReward{    
    __weak typeof(self)weakSelf = self;
    [[ZHHttpTools share]POST:RelationReward parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *code = [ZHHttpTools invokeCode:responseObject];
        NSString *message = [ZHHttpTools invokeMessage:responseObject];
        if ([code isEqualToString:@"200"]) {
            weakSelf.arr2 = [ZHShareItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"relation"]];
        }else{
            ZYLog(@"%@",message);
        }
       //注意这里,failure中也得添加一样的,用于标注信号量
        dispatch_semaphore_signal(semaphore);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ZYLog(@"%@",error);
        dispatch_semaphore_signal(semaphore);
    }];
}

你可能感兴趣的:(信号量实现AFNetworking网络请求顺序执行)