美文网首页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://blog.csdn.net/dingqk/article/details/7787832...

  • 多线程

    iOS中的几种多线程GCD1、GCD分为任务和队列,任务(同步,异步)队列(串行,并发),同步串行,同步主队列的情...

  • iOS串行队列

    //首先创建5个串行队列dispatch_queue_t serialQueue1 = dispatch_queu...

  • iOS - 串行队列

    背景:开发人员在需要开启线程处理任务时,大多都采用了全局队列默认优先级来处理,所以项目中积累了大量的全局队列默认优...

  • iOS开发之GCD并发队列

    iOS开发多线程之GCDiOS开发之GCD同步任务加强iOS开发之GCD串行队列iOS开发之GCD并发队列 03 ...

  • iOS开发多线程之GCD

    iOS开发多线程之GCDiOS开发之GCD同步任务加强iOS开发之GCD串行队列iOS开发之GCD并发队列 GCD...

  • iOS开发之GCD同步任务加强

    iOS开发多线程之GCDiOS开发之GCD同步任务加强iOS开发之GCD串行队列iOS开发之GCD并发队列 004...

  • iOS开发之GCD串行队列

    iOS开发多线程之GCDiOS开发之GCD同步任务加强iOS开发之GCD串行队列iOS开发之GCD并发队列 实例d...

  • 谈谈队列和多线程的使用原理

    在iOS中队列分为以下几种: 串行队列:队列中的任务只会顺序执行; dispatch_queue_tq = dis...

  • dispatch_set_target_queue让多个串行队列

    在好多网络上的文章里面都有提到将多个串行队列使用dispatch_set_target_queue设置一个串行队列...

网友评论

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

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