0

I'm trying to fill an array when fetching users from Firebase. When I set a breakpoint, I can see, that all users are appended to the array, but when the debugger is done, the array is empty again.

func firebaseRequest(completionHandler: @escaping (Result<[User], Error>) -> Void) {
        
        var tempFirebaseUsers = [User]()
        
        self.firebaseFunctions.fetchUsers { (userFB, error) in
            
            if let user = userFB {
                print("User: ", user)
                tempFirebaseUsers.append(user)
            } else if let error = error{
                completionHandler(.failure(error))
                return
            }
            
        }

        completionHandler(.success(tempFirebaseUsers))
        return
    }

1 Answer 1

1

You're calling your completion handler too early. When your completionHandler(.success(tempFirebaseUsers)) runs, the tempFirebaseUsers.append(user) hasn't run yet.

To fix this, move the call to the completion handler into the callback:

func firebaseRequest(completionHandler: @escaping (Result<[User], Error>) -> Void) {
    
    var tempFirebaseUsers = [User]()
    
    self.firebaseFunctions.fetchUsers { (userFB, error) in
        
        if let user = userFB {
            print("User: ", user)
            tempFirebaseUsers.append(user)
            completionHandler(.success(tempFirebaseUsers))
        } else if let error = error{
            completionHandler(.failure(error))
            return
        }
        
    }

    return
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, thanks! Okay, the array passed in the completionHandler contains values now. The problem is, that the completionHandler is called for each user, since this fetchUsers function returns one user at a time. How can I say: Wait to send the completionHandler, until every user is fetched and appended to the tempFirebaseUsers array?
There's only one call in the snippet you shared. But if you do this multiple times, I typically keep a counter, increment that inside the loop, and only call the completion handler once I've read the required number of documents. Here's one example of doing that: stackoverflow.com/questions/62666162/…
I've managed to fix it. I rewrote my firebaseFunctions.fetchUsers. THANKS A LOT for helping me with my completion handler!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.