iOS多个网络请求完成后执行下一步

2019/6/22 posted in  Swift
  • 使用GCD的DispatchGroup实现

每次进入异步任务前都要调用enter方法,完成后执行leave,enterleave都是成对存在,如果enterleave次数不是一一对应,group就不会销毁。

let group = DispatchGroup()

for i in 0..<10 {
    // 创建异步任务
    let task = DispatchQueue.init(label: "this is \(i) queue")
    // 进入标记
    group.enter()
    
    task.async {
        sleep(1)
        // 打印信息
        print("i \(i), current thread: \(Thread.current)")
        // 退出
        group.leave()
    }
}

group.notify(queue: DispatchQueue.main) {
    print("所有任务结束, current thread: \(Thread.current)")
}
打印信息:
i 6, current thread: <NSThread: 0x60000297eac0>{number = 5, name = (null)}
i 2, current thread: <NSThread: 0x600002951180>{number = 8, name = (null)}
i 0, current thread: <NSThread: 0x600002958280>{number = 6, name = (null)}
i 3, current thread: <NSThread: 0x600002961640>{number = 9, name = (null)}
i 5, current thread: <NSThread: 0x6000029582c0>{number = 10, name = (null)}
i 7, current thread: <NSThread: 0x600002958300>{number = 7, name = (null)}
i 1, current thread: <NSThread: 0x6000029618c0>{number = 12, name = (null)}
i 4, current thread: <NSThread: 0x600002966980>{number = 11, name = (null)}
i 8, current thread: <NSThread: 0x600002969b00>{number = 13, name = (null)}
i 9, current thread: <NSThread: 0x6000029581c0>{number = 14, name = (null)}
所有任务结束, current thread: <NSThread: 0x60000295e8c0>{number = 1, name = main}