Search code examples
swiftswift3

How to check if two asynchronous tasks are done with success


What is the best and easiest way to implement this flowchart in a function? Right now I'm using two dispatch groups but I need to check if they're both done, and not only when they finish.

If they are done then:

  • friends array will have elements
  • nicknames array will have elements

Flowchart

note: FB is Facebook and FIR is Firebase database


Solution

  • You could do this using DispatchGroup. Try the following playground;

    import UIKit
    import XCPlayground
    
    let dispatchGroup = DispatchGroup.init()
    
    for index in 0...4 {
        dispatchGroup.enter()
        let random = drand48()
        let deadline = DispatchTime.now() + random/1000
        print("entered \(index)")
        DispatchQueue.global(qos: .background).asyncAfter(deadline: deadline, execute: {
            print("leaving \(index)")
            dispatchGroup.leave()
        })
    }
    
    dispatchGroup.notify(queue: .global()) {
        print("finished all")
    }
    

    which should output something similar to

    entered 0
    leaving 0
    entered 1
    entered 2
    leaving 1
    leaving 2
    entered 3
    leaving 3
    entered 4
    leaving 4
    finished all