0

I am having trouble figuring out how to modify my code to take into account the fact that Firebase runs asynchronously.

func checkIfFriends(_ SearchUserUID: String) -> Bool {
    
    var friendArray: [String]?
    
    currentUserDetails.getDocument { (document, error) in
            if let document = document, document.exists {
                    friendArray = document.data()!["Friends"] as? [String]
                }
            }

        if let friends = friendArray {
            return friends.contains(SearchUserUID)
        }

    return false
    
}

currentUserDetails is the document of the current user that stores an array of friends that the current user has under the String, "Friends", where each element of the array is the UID of the friend. I would like to check if two users are friends by first retrieving the array of friends of the current user, and then checking if that array contains the UID of the friend we are searching for.

The issue is that

        currentUserDetails.getDocument { (document, error) in
            if let document = document, document.exists {
                    friendArray = document.data()!["Friends"] as? [String]
                }
            }

runs asynchronously so my friendArray is considered to be nil and my method always returns false. I am very confused as to how I can modify such methods to return values and take into account the asynchronous nature of Firebase data retrieval. Could someone help me out? Thank you very much!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user844288
  • 17
  • 1
  • 6
  • When dealing with asynchronous callbacks, there is one simple rule to follow: any code that needs the data from the database needs to be inside the callback from the database (or be called from there). By the time your `return false` runs the `friendArray = document....` hasn't been executed yet. This means you will *never* be able to simply return a value that has been loaded asynchronously, and you should instead pass in a callback to your `checkIfFriends` method that you call with the boolean result. Alternatively you can use a dispatch group. – Frank van Puffelen Jun 24 '21 at 14:35
  • Note that this has been covered quite some times already, so I also recommend spending some time studying other questions about [asynchronous behavior with Firestore in Swift](https://stackoverflow.com/search?q=%5Bgoogle-cloud-firestore%5D%5Bswift%5D+asynchronous). – Frank van Puffelen Jun 24 '21 at 14:35

0 Answers0