美文网首页
多个网络请求

多个网络请求

作者: 哲逗年 | 来源:发表于2018-04-18 10:20 被阅读0次

    在开发中,很容易遇到这样的需求,需要同时做多个网络请求,所有网络请求都完成后才能进行下一步的操作。如下载多个图片,下载完了才能展示。

    下面分几种情况来分析各个方案的特点

    1.不做任何处理去连续请求一个接口10次

    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    for (int i = 0; i < 10; i++) {
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%d--%d",i,i);
        }];
        [task resume];
    }
    
    NSLog(@"end~~~");
    

    运行结果:

    end~~~
    0--0
    4--4
    5--5
    1--1
    6--6
    2--2
    3--3
    7--7
    8--8
    9--9
    

    很明显,无任何处理情况下,end最先被打印出来,由于网络请求的异步回调,然后各个网络请求的回调顺序是无序的。

    2.使用GCD的dispatch_group_t

    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0; i < 10; i++) {
        dispatch_group_enter(group);
        
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%d--%d",i,i);
            dispatch_group_leave(group);
        }];
        [task resume];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"end~~~");
    });
    

    运行结果:

    2018-04-18 09:07:52.602215+0800 GCDDEMO[87404:36213044] 0--0
    2018-04-18 09:07:52.640131+0800 GCDDEMO[87404:36213040] 4--4
    2018-04-18 09:07:52.661871+0800 GCDDEMO[87404:36213087] 5--5
    2018-04-18 09:07:52.684844+0800 GCDDEMO[87404:36213040] 1--1
    2018-04-18 09:07:52.694179+0800 GCDDEMO[87404:36213087] 6--6
    2018-04-18 09:07:52.694784+0800 GCDDEMO[87404:36213087] 2--2
    2018-04-18 09:07:52.697034+0800 GCDDEMO[87404:36213087] 3--3
    2018-04-18 09:07:52.697424+0800 GCDDEMO[87404:36213043] 7--7
    2018-04-18 09:07:52.704872+0800 GCDDEMO[87404:36213043] 8--8
    2018-04-18 09:07:52.705207+0800 GCDDEMO[87404:36213042] 9--9
    2018-04-18 09:07:52.705313+0800 GCDDEMO[87404:36212936] end~~~
    

    从结果可以看出,end确实是在所有网络请求之后才输出来的,这几本可以符合我们的需求。

    我们只添加了4行代码

    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);// 每次网络请求前先enter
    dispatch_group_leave(group);// 网络请求后leave
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    // 等所有的enter的都leave后,会执行dispatch_group_notify的block
    });
    

    注意:enter和leave必须要配合使用,否则group会一直存在。

    3.使用GCD的dispatch_semaphore_t

    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    __block NSInteger count = 0;
    for (int i = 0; i < 10; i++) {
        
        
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%d--%d",i,i);
            count ++;
            if (count == 10) {
                dispatch_semaphore_signal(sem);
            }
            
        }];
        [task resume];
    }
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"end~~~");
    });
    

    输出结果跟dispatch_group_t是一样的,也是满足我们的需求,在这个方法中,我们使用了

    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    dispatch_semaphore_signal(sem);
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    

    对这三句代码可以这样理解:dispatch_semaphore信号量为基于计数器的一种多线程同步机制。如果semaphore计数大于等于1,计数-1,返回,程序继续运行。如果计数为0,则等待。dispatch_semaphore_signal(semaphore)为计数+1操作,dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)为设置等待时间,这里设置的等待时间是一直等待。

    对以上代码通俗一点就是,一开始为0,等待,等10个网络请求都完成了,dispatch_semaphore_signal(semaphore)为计数+1,然后计数-1返回,程序继续执行(这里也就是为什么有个count变量的原因,记录网络回调的次数,回调10次之后再发信号量,使后面的程序继续运行)。

    4.考虑新需求,10个网络请求顺序回调
    以上都是顺序执行,异步回调。
    现在需求需要顺序回调,即执行完第一个网络请求后,第二个网络请求回调才可被执行。

    4.1.使用NSOperation
    这种情况只适用于非网络请求异步回调的方式,如果是网络请求异步回调方式,执行结果依然是异步的,无序的。

    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSMutableArray *operationArray = [NSMutableArray array];
    
    for (int i = 0; i < 10; i++) {
        
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
           
            NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                NSLog(@"%d--%d",i,i);
                
            }];
            [task resume];
            
            NSLog(@"noRequest-%d",i);
        }];
        
        [operationArray addObject:operation];
        if (i > 0) {
            NSBlockOperation *operation1 = operationArray[i - 1];
            NSBlockOperation *operation2 = operationArray[i];
            [operation2 addDependency:operation1];
        }
    }
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperations:operationArray waitUntilFinished:NO];
    

    运行结果:

    2018-04-18 10:04:04.705267+0800 GCDDEMO[88188:36384293] noRequest-0
    2018-04-18 10:04:04.705523+0800 GCDDEMO[88188:36384297] noRequest-1
    2018-04-18 10:04:04.705726+0800 GCDDEMO[88188:36384295] noRequest-2
    2018-04-18 10:04:04.714099+0800 GCDDEMO[88188:36384297] noRequest-3
    2018-04-18 10:04:04.714264+0800 GCDDEMO[88188:36384297] noRequest-4
    2018-04-18 10:04:04.714409+0800 GCDDEMO[88188:36384297] noRequest-5
    2018-04-18 10:04:04.714548+0800 GCDDEMO[88188:36384295] noRequest-6
    2018-04-18 10:04:04.714675+0800 GCDDEMO[88188:36384297] noRequest-7
    2018-04-18 10:04:04.714876+0800 GCDDEMO[88188:36384295] noRequest-8
    2018-04-18 10:04:04.715012+0800 GCDDEMO[88188:36384295] noRequest-9
    2018-04-18 10:04:05.004360+0800 GCDDEMO[88188:36384296] 0--0
    2018-04-18 10:04:05.043685+0800 GCDDEMO[88188:36384293] 4--4
    2018-04-18 10:04:05.065200+0800 GCDDEMO[88188:36384293] 5--5
    2018-04-18 10:04:05.087599+0800 GCDDEMO[88188:36384297] 1--1
    2018-04-18 10:04:05.096894+0800 GCDDEMO[88188:36384293] 6--6
    2018-04-18 10:04:05.098786+0800 GCDDEMO[88188:36384295] 2--2
    2018-04-18 10:04:05.099004+0800 GCDDEMO[88188:36384295] 3--3
    2018-04-18 10:04:05.099597+0800 GCDDEMO[88188:36384297] 7--7
    2018-04-18 10:04:05.108636+0800 GCDDEMO[88188:36384294] 8--8
    2018-04-18 10:04:05.111886+0800 GCDDEMO[88188:36384295] 9--9
    

    结果:只要不是类似网络请求异步回调的方式,用NSOperation是可以满足需求的

    **4.2使用信号量semaphore完成需求

    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    
    for (int i = 0; i < 10; i++) {
        
        
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%d--%d",i,i);
            dispatch_semaphore_signal(sem);
        }];
        [task resume];
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"end~~~");
    });
    

    运行结果

    2018-04-18 10:08:07.731511+0800 GCDDEMO[88273:36400543] 0--0
    2018-04-18 10:08:07.743634+0800 GCDDEMO[88273:36400510] 1--1
    2018-04-18 10:08:07.757264+0800 GCDDEMO[88273:36400510] 2--2
    2018-04-18 10:08:07.769691+0800 GCDDEMO[88273:36400543] 3--3
    2018-04-18 10:08:07.781623+0800 GCDDEMO[88273:36400510] 4--4
    2018-04-18 10:08:07.792994+0800 GCDDEMO[88273:36400506] 5--5
    2018-04-18 10:08:07.805168+0800 GCDDEMO[88273:36400506] 6--6
    2018-04-18 10:08:07.816233+0800 GCDDEMO[88273:36400506] 7--7
    2018-04-18 10:08:07.827581+0800 GCDDEMO[88273:36400510] 8--8
    2018-04-18 10:08:07.839853+0800 GCDDEMO[88273:36400506] 9--9
    2018-04-18 10:08:07.860696+0800 GCDDEMO[88273:36400401] end~~~
    

    这里的代码跟3的需求的代码唯一不同点就是dispatch_semaphore_wait(semaphore)放到了每一次循环的后面,而不是放到10次结束后。

    流程就是
    遍历-> 发起任务->等待->任务完成信号量加1->等待结束,开始下一个任务
    发起任务->等待->任务完成信号量加1->等待结束,开始下一个任务
    发起任务->等待->任务完成信号量加1->等待结束,开始下一个任务
    一直循环到结束。

    但是这样有个缺点,就是耗时会比较长,因为一个网络请求结束后才能发起下一个网络请求,而dispatch_semaphore_wait(sem,DISPATCH_TIME_FOREVER)是会阻塞线程的,我们如果需要在网络请求完成后修改UI,那这种方式会影响我们的界面交互。

    原文请挪步这里

    相关文章

      网友评论

          本文标题:多个网络请求

          本文链接:https://www.haomeiwen.com/subject/hvgmkftx.html