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!