简体   繁体   中英

Swift Async With Completion Block

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?

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM