美文网首页
多弹窗按顺序依次弹出

多弹窗按顺序依次弹出

作者: 冰点雨 | 来源:发表于2020-08-18 09:37 被阅读0次

    通过dispatch_queue_t及dispatch_semaphore_t实现

     //创建一个队列,串行并行都可以,主要为了操作信号量
        dispatch_queue_t queue = dispatch_queue_create("com.se7en.alert", DISPATCH_QUEUE_SERIAL);
        dispatch_async(queue, ^{
        //创建一个初始为0的信号量
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
            NSLog(@"弹框1");
            [NSThread sleepForTimeInterval:1];
        //第一个弹框,UI的创建和显示,要在主线程
        dispatch_async(dispatch_get_main_queue(), ^{
         UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"弹框1" message:@"第一个弹框" preferredStyle:UIAlertControllerStyleAlert];
         [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
         //点击Alert上的按钮,我们发送一次信号。
         dispatch_semaphore_signal(sema);
         }]];
         [self presentViewController:alert animated:YES completion:nil];
        });
        
        //等待信号触发,注意,这里是在我们创建的队列中等待
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            NSLog(@"弹框2");
            [NSThread sleepForTimeInterval:1];
        //上面的等待到信号触发之后,再创建第二个Alert
        dispatch_async(dispatch_get_main_queue(), ^{
         UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"弹框2" message:@"第二个弹框" preferredStyle:UIAlertControllerStyleAlert];
         [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
         dispatch_semaphore_signal(sema);
         }]];
         [self presentViewController:alert animated:YES completion:nil];
        });
        
        //同理,创建第三个Alert
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            NSLog(@"弹框3");
            [NSThread sleepForTimeInterval:1];
        dispatch_async(dispatch_get_main_queue(), ^{
         UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"弹框3" message:@"第三个弹框" preferredStyle:UIAlertControllerStyleAlert];
         [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
         dispatch_semaphore_signal(sema);
         }]];
         [self presentViewController:alert animated:YES completion:nil];
        });
        });
    

    结果:

    2020-08-03 14:10:17.143774+0800 GCDDemo[4731:161332] 弹框1
    2020-08-03 14:10:20.254767+0800 GCDDemo[4731:161332] 弹框2
    2020-08-03 14:10:22.363951+0800 GCDDemo[4731:161332] 弹框3
    

    相关文章

      网友评论

          本文标题:多弹窗按顺序依次弹出

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