iOS 网络请求顺序执行

  • 参考文章
    (iOS-网络请求依次执行,NSOperationQueue与dispatch_semaphore)[https://www.jianshu.com/p/342b2ffbdd97]
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 2;
    NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{
            [self updateLatestNews];
    }];
    NSBlockOperation *operationB = [NSBlockOperation blockOperationWithBlock:^{
            [self updateEveryNews];
    }];
    [operationB addDependency:operationA];
    [queue addOperation:operationA];
    [queue addOperation:operationB];

只适合在单个线程任务执行时使用,但实际项目不实用

GCD中的信号量dispatch_semaphore
dispatch_semaphore信号量为基于计数器的一种多线程同步机制。用于解决在多个线程访问共有资源时候,会因为多线程的特性而引发数据出错的问题。

如果semaphore计数大于等于1,计数-1,返回,程序继续运行。如果计数为0,则等待。
dispatch_semaphore_signal(semaphore)为计数+1操作。dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)为设置等待时间,这里设置的等待时间是一直等待。

- (void)fetchHomeDataWithSucceed:(ZJIHomeHandle)succeedBlock error:(ErrorHandle)errorBlock{
     dispatch_semaphore_t sema = dispatch_semaphore_create(0); 
    
    NSString *urlString = @"https://news-at.zhihu.com/api/4/news/latest";
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *sharedSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest: request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data && (error == nil)){
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            NSError *err;
            ZJIHomeModel *homeModel = [[ZJIHomeModel alloc]initWithDictionary:dict error:&err];
            succeedBlock(homeModel);
            
            dispatch_semaphore_signal(sema);
        }
        else{
            errorBlock(error);
            
            dispatch_semaphore_signal(sema);
        }
    }];
    [dataTask resume];
    
    **dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);******
}

在网络请求里写上述黑体代码就会在这个网络请求完成之后才执行下一个网络请求

你可能感兴趣的:(iOS 网络请求顺序执行)