iOS开发网络篇:GCD实战之多个网络请求的并发

发布于 2019-12-26 14:13:08

GCD实战之多个网络请求的并发
第一种GCD 方式:

// 创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// 创建全局并行
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{

    // 请求一
    [loginCode getUserInfoWithNick:nil andUserId:kUserId onSuc:^(id data) {
        NSLog(@"yue");
        dispatch_semaphore_signal(semaphore);

    } andFail:^(NSError *error) {       
    }];

});
dispatch_group_async(group, queue, ^{

    // 请求二
    [CommodityViewModel getPriceTransformForIntegral:nil onSuccess:^(id data) {

        NSLog(@"duihuan11");
        dispatch_semaphore_signal(semaphore);

    } onFailure:^(NSError *error) {
    }];
});
dispatch_group_async(group, queue, ^{

    // 请求三
    [CommodityViewModel getPriceTransformForIntegral:nil onSuccess:^(id data) {
        NSLog(@"duihuan22");
        dispatch_semaphore_signal(semaphore);

    } onFailure:^(NSError *error) {            
    }];
});

dispatch_group_notify(group, queue, ^{

    // 三个请求对应三次信号等待
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    //在这里 进行请求后的方法,回到主线程
    dispatch_async(dispatch_get_main_queue(), ^{

        //更新UI操作

    });


});

第二种 通过请求数量计数
定义一个block

typedef void(^Complete)();

将block作为类的属性

@property (copy, nonatomic) Complete complete;

实现方式:

NSInteger requestCount = 0;

//第一个网络请求
[CommodityViewModel getPriceTransformForIntegral:nil onSuccess:^(id data) {
    NSLog(@"duihuan11");
    requestCount++;
    if (self.complete) {
        self.complete();
    }
} onFailure:^(NSError *error) {
}];

//第二个网络请求
[CommodityViewModel getPriceTransformForIntegral:nil onSuccess:^(id data) {
    NSLog(@"duihuan22");
    requestCount++;
    if (self.complete) {
        self.complete();
    }
} onFailure:^(NSError *error) {
}];

//第三个网络请求
[CommodityViewModel getPriceTransformForIntegral:nil onSuccess:^(id data) {
    NSLog(@"duihuan33");
    requestCount++;
    if (self.complete) {
        self.complete();
    }
} onFailure:^(NSError *error) {
}];

self.complete = ^{

        //请求网络的数量等于3表示三个网络请求已完成
        if (requestCount == 3) {

            //在这里 进行请求后的方法,回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{

                //更新UI操作

            });

        }

    };

————————————————
版权声明:本文为CSDN博主「sailip」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Yj_sail/article/details/70174467

0 条评论

发布
问题

官网
微信

官方微信