与完成块的Swift异步

时间:2018-05-09 17:15:05

标签: swift asynchronous completion-block dispatch-queue

我有两个执行异步的函数。

我尝试将它们“同步”:DispatchGroup和DispatchQueue

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let group = DispatchGroup()

queue.async(group: group) {
    //func1
}

queue.async(group: group) {
    //func2
}

group.notify(queue: queue) {
    print("#3 finished")
}

Func1和Func2仅调用:

class func getDataFromUrl( url: URL, completion: @escaping ( Data?, URLResponse?, Error? ) -> ( ) )
    {
        URLSession.shared.dataTask( with: url )
        {
            data, response, error in

            completion( data, response, error )
        }.resume( )
    }

但问题是我不知道如何等待queue.async中的完成块..

任何人都有任何想法吗?

1 个答案:

答案 0 :(得分:0)

您只需使用DispatchGroup

即可
let group = DispatchGroup()

group.enter()
API.getDataFromUrl(...) {
   // #1 Call finished
   group.leave()
}

group.enter()
API.getDataFromUrl(...) {
   // #2 Call finished
   group.leave()
}

group.notify(queue: .main)  {
    print("Both call finished")
}