美文网首页GCD
iOS网络串行队列

iOS网络串行队列

作者: 白色天空729 | 来源:发表于2019-10-21 10:54 被阅读0次

    参考链接:https://blog.csdn.net/dingqk/article/details/77878322
    https://juejin.im/post/5a9e57af6fb9a028df222555
    https://www.cnblogs.com/yajunLi/p/6274282.html

    #import "ViewController.h"
    #import "AFNetworking.h"
    
    @interface ViewController () {
        NSMutableArray *_dataSource;
    }
    @property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
    
    @end
    
    @implementation ViewController
    
    - (void)download {
    NSArray *downloadArray =
    [@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10
    .com%2F28ea2e5cf17173f84ef74064e95627cc3ba75fe627e71-hKNgS4_fw6
    @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_100
    .com%2F5f362385b8ffedc49172da5b056b03a5b54e191830b59-FM6lGh_fw6
    @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_100
    .com%2F20110524%2F2457331_092725729000_2.jpg",
    @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_100
    .com%2Fwallpaper%2F2018-08-16%2F5b750e40cbed0.jpg"];        // 设置最大线程数
        
        
        // 创建一个队列
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        
        // 设置最大线程数
        queue.maxConcurrentOperationCount = 1;
        
        for (NSInteger i = 0; i < downloadArray.count; i++) {
            //创建一个队列数组
            NSMutableArray *operaQueueArray = [NSMutableArray array];
            
            NSBlockOperation *blockOpera = [NSBlockOperation blockOperationWithBlock:^{
                dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //默认创建的信号为0
                //1.创建会话管理者
                AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
                NSURL *url = [NSURL URLWithString:downloadArray[I]];
                
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                    
                    //监听下载进度
                    //completedUnitCount 已经下载的数据大小
                    //totalUnitCount     文件数据的中大小
                    NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
                    
                } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
                    
                    NSLog(@"targetPath:%@",targetPath);
                    
                    NSLog(@"fullPath:%@",fullPath);
                    dispatch_semaphore_signal(semaphore); //这里请求成功信号量 +1 为1
                    
                    
                    return [NSURL fileURLWithPath:fullPath];
                    
                } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                    NSLog(@"%@",filePath);
                    dispatch_semaphore_signal(semaphore); //这里请求成功信号量 +1 为1
    
                }];
                
                //3.执行Task
                [download resume];
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); //走到这里如果信号量为0 则不再执行下面的代码 一直等待 信号量不是0 出现 才会执行下面代码,然后信号量为 - 1
            }];
            //将创建的任务添加到数组中
            [operaQueueArray addObject:blockOpera];
            
            
            //添加依赖关系
            for (int i = 0; i < operaQueueArray.count; i++) {
                if (i > 0) {
                    [operaQueueArray[i] addDependency:operaQueueArray[i - 1]];
                }
            }
            
            [queue addOperations:operaQueueArray waitUntilFinished:NO];
            [queue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];
    
        };
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self download];
        NSLog(@"====");
    }
    
    //监听网络请求
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
        
        if ([keyPath isEqualToString:@"operationCount"]) {
            NSOperationQueue *queue = (NSOperationQueue *)object;
            if (queue.operationCount == 0) {
                //主线程刷新界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"%d===",__LINE__);
                });
            }
        }
    }
    
    @end
    
    

    效果图:


    image.png

    相关文章

      网友评论

        本文标题:iOS网络串行队列

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