Search code examples
requestwaitxcode11swift5operation

How to wait for request to finish before execute the next operation (Xcode 11)


I have a code that allows fetching data on firebase. I need to wait until the request has been satisfied to execute the next operation.

I have tried something like this:

var a = [String : Any]()
let group = DispatchGroup()
group.enter()

DispatchQueue.main.async {
    dbRef.child("results/users").observeSingleEvent(of: .value) { (snapshot) in
        if let res = snapshot.value as? [String:Any] {
            a = res
        }
    }
}

group.notify(queue: .main) {
    print(a)
}

But it does not work: I expected that this displays the value of a. (The code used to retrieve data from firebase works.) Instead, nothing is displayed.

Does somebody have an idea? Thank you


Solution

  • You can solve it with this:

    var a: [String:Any]
    
    func myFunction(completion:@escaping (Bool) -> () ) {
    
        DispatchQueue.main.async {
            dbRef.child("results/users").observeSingleEvent(of: .value) { (snapshot) in
            if let res = snapshot.value as? [String:Any] {
                a = res
            }
        }
    }
    
    
    myFunction { (status) in
        if status {
            print(a!)
        }
    }