I'm trying to pull the number of mutual friends that I have with any given userID. I first pulled all my friends from Firebase and then I pulled the userID's friends. I'm just not sure how to count the number of mutual friends from there. Please let me know if I'm going about it the wrong way.
func fetchMutualFriends(myID: String, userID: String) {
let myID = Auth.auth().currentUser!.uid
let postRef = self.databaseRef.child("friends").child(myID)
postRef.observe(.value, with: { (snapshot) in
for childSnapshot in snapshot.children {
print(childSnapshot)
}
})
let postRef1 = self.databaseRef.child("friends").child(friendID)
postRef1.observe(.value, with: { (snapshot) in
for childSnapshot in snapshot.children {
print(childSnapshot)
}
})
}
Firebase structure
root/
|___ friends/
| |___ myID
| |___ friendID1
| |___ friendID1
| |___ myID
It would help a lot if you post the structure of your database in your question.
I assume it looks something like this:
I added a lot of comments in the code below to make it easier for you to see every step.
So, this is how you could write your
fetchMutualFriends
method:You have to use numChildren() function which returns the number of child properties of a DataSnapshot. Assume we have the following data in the Database:
If I want to know the number of childs of name for example :
If I want to know the number of childs of first for example :
Hope it will guide you.
Since the actual struture is not clear, let's assume a standard structure like this
As you can see, user 0 is friends with user_1, user_2 and user_3, and likewise in their nodes those users are friends with user_0.
If we want to keep this structure then finding the intersection of two users mutual friends is pretty easy.
Suppose we want to find which friends user_0 and user_2 have in common. Looking at the structure we find it's
How do we do that in code?
Here's how that code works: We start with a reference to the two users friends lists we want to compare
Using observeSingleEvent, the first users friends list is read and the keys (user_1, user_2 etc) are stored in an array. That is done my mapping (iterating over) each key: value pair to capture the key. That array is converted to a Set var.
We do the same thing for the second user - noting it's important we do that within the first closure so we are guaranteed the results from the first user are complete. Those results are mapped to an array and the made into a Set.
Then, the magic of leveraging the intersection function of a Set and then print the mutual friends (sorted)