iOS 等待多任务完成后,执行下一步操作。

个人学习笔记:多图片上传。

//

//  ViewController.m

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *showLabel;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    printf("处理前创建信号量,开始循环异步请求操作\n");

    NSMutableArray *tampArray =[NSMutableArray new];

    __weaktypeof(self) weakself =self;

    // 1.创建一个串行队列,保证for循环依次执行

    dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);

    // 2.异步执行任务

    dispatch_async(serialQueue, ^{

        // 3.创建一个数目为1的信号量,用于“卡”for循环,等上次循环结束在执行下一次的for循环

        dispatch_semaphore_t sema = dispatch_semaphore_create(0);

        for(inti = 0; i<5; i++) {

            // 开始执行for循环,让信号量-1,这样下次操作须等信号量>=0才会继续,否则下次操作将永久停止

            printf("信号量等待中\n");

            // 模拟一个异步任务

            NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://github.com"]];

            NSURLSession *session = [NSURLSession sharedSession];

            NSURLSessionDataTask*dataTask = [sessiondataTaskWithRequest:urlRequestcompletionHandler:^(NSData*_Nullabledata,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) {

            // 本次for循环的异步任务执行完毕,这时候要发一个信号,若不发,下次操作将永远不会触发

                [tampArrayaddObject:@(i)];

                [weakselfchangeText:[NSStringstringWithFormat:@"本次耗时操作完成,信号量+1 %@\n",[NSThread currentThread]]];

                NSLog(@"本次耗时操作完成,信号量+1 %@\n",[NSThread currentThread]);

                dispatch_semaphore_signal(sema);

            }];

            [dataTaskresume];

            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

        }

        printf("其他操作");

        [weakselfchangeText:@"其他操作"];

        for(NSNumber*numintampArray) {

            NSLog(@"所有操作完成后的操作--->  %@\n",num);

        }

    });

}

-(void)changeText:(NSString*)text{

    __weak typeof(self) wakself = self;

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        wakself.showLabel.text= text;

    }];

}

@end

版权声明:本文为CSDN博主「扬帆追梦人」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_34417314/article/details/80449484

你可能感兴趣的:(iOS 等待多任务完成后,执行下一步操作。)