Swift Async With Completion Block

浪子不回头ぞ 提交于 2019-12-03 22:32:57

问题


I have two functions that executes async.

I tried to "syncronize" them with: DispatchGroup and 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 and Func2 are only calls of:

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

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

But the problem is that i do not know how to wait for the completion block in the queue.async ..

Anyone has any ideea?


回答1:


You can simply use only the 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")
}


来源:https://stackoverflow.com/questions/50258778/swift-async-with-completion-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!