I want to take the currentUser's userId and add it as a child to all their friend's data- in Firebase with Swift

雨燕双飞 提交于 2020-01-06 06:57:20

问题


In my Firebase database, the parent data is all the users' userIds. They each have a child("friends") which contains a list of all their friends' userIds.

I want to get each currentUser's friends' userIds and add the currentUser's userId to each of their friends' child("closeFriends") node

This is how my data structure looks:

users
    10XeC8j6OCcFTKj8Dm7lR7dVnkf1
        email: "Dummy19@gmail.com"
        fcmToken: "cBW9XhpYqio:APA91bF6K5YgRj0PgyDCoApNpIWGO4icwFg..."
        friends
            ekFjYJU8OWTbYnQXVzhcxVE0wBP2: true
        profileImageUrl: "https://firebasestorage.googleapis.com/v0/b/jar..."
        username: "Dummy19"
    ePt3MSOuk6ZYDfekewmPlG4LgcU2
        email: "Dummy20@gmail.com"
        fcmToken: "cBW9XhpYqio:APA91bF6K5YgRj0PgyDCoApNpIWGO4icwFg..."
        friends
            ekFjYJU8OWTbYnQXVzhcxVE0wBP2: true
            u43NtDYmqeTxafmLYjxxt60ngUo1: true
        profileImageUrl: "https://firebasestorage.googleapis.com/v0/b/jar..."
        username: "Dummy20"
    ekFjYJU8OWTbYnQXVzhcxVE0wBP2
        email: "Dummy18@gmail.com"
        fcmToken: "cF-b_Fd8Ufc:APA91bG9bir1o_jdJdfB35l9g9HlNNTNHPM..."
        friends
            10XeC8j6OCcFTKj8Dm7lR7dVnkf1: true
            ePt3MSOuk6ZYDfekewmPlG4LgcU2: true
        profileImageUrl: "https://firebasestorage.googleapis.com/v0/b/jar..."
        username: "Dummy18"
    u43NtDYmqeTxafmLYjxxt60ngUo1
        email: "Dummy21@gmail.com"
        fcmToken: "cBW9XhpYqio:APA91bF6K5YgRj0PgyDCoApNpIWGO4icwFg..."
        friends
            ePt3MSOuk6ZYDfekewmPlG4LgcU2: true
        profileImageUrl: "https://firebasestorage.googleapis.com/v0/b/jar..."
        username: "Dummy21"

And I want 'closeFriends' to be a node with userIds just like friends is already.

These are my reference variables and functions:

let userReference = Database.database().reference().child("users")

var currentUserReference: DatabaseReference {
    let id = Auth.auth().currentUser!.uid
    return userReference.child("\(id)")
}

var currentUserFriendsReference: DatabaseReference {
    return currentUserReference.child("friends")
}

var currentUserCloseFriendsReference: DatabaseReference {
    return currentUserReference.child("closeFriends")
}

var currentUserId: String {
    let uid = Auth.auth().currentUser!.uid
    return uid
}

func getCurrentUser(_ completion: @escaping (User) -> Void) {
    currentUserReference.observeSingleEvent(of: DataEventType.value) { (snapshot) in
        let email: String = snapshot.childSnapshot(forPath: "email").value as! String
        let uid = snapshot.key

        let username = snapshot.childSnapshot(forPath: "username").value as! String

        let profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String

        completion(User(uid: uid, userUsername: username, userProfileImageUrl: profileImageUrl, userEmail: email))
    }
}

func getUser(_ userId: String, completion: @escaping (User) -> Void) {
    userReference.child(userId).observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
        let email = snapshot.childSnapshot(forPath: "email").value as! String
        let uid = snapshot.key

        // Did the same thing here as in the above function
        let username = snapshot.childSnapshot(forPath: "username").value as! String

        let profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String

        completion(User(uid: uid, userUsername: username, userProfileImageUrl: profileImageUrl, userEmail: email))
    })
}

var closeFriendList = [User]()

I tried this for loop, but it did nothing:

func addCurrentUserToCloseFriendsLists(_ userId: String){
    for friend in friendList{
        let id = friend.uid
        self.getUser(id) { (user) in
            self.closeFriendList.append(user)
            self.userReference.child(userId).child("closeFriends").child(self.currentUserId).setValue(true)
        }
    }

For reference, friendList is the list of friends created in another file (my "FriendSystem").

I'm sure there's another way to fetch all the user's friends and then run a loop to add the currentUser to all those friends' child("closeFriends"), I just haven't been able to figure it out.

Super stuck on this, hope you can help! Thanks!


回答1:


I want to get each currentUser's friends' userIds and add the currentUser's userId to each of their friends' child("closeFriends") node

Let start with a simple users structure similar to yours:

users
   uid_0
      name: "Larry"
      friends:
         uid_1: true
         uid_2: true
   uid_1
       name: "Moe"
   uid_2
       name: "Curly"

The idea is to go through this users (the current user) friends list and add this users uid to the other users friends list. In this example, I am just creating a 'friends' node for each user but you can make it 'closeFriends' or whatever name you want.

Here's the code to do that

let thisUserId = "uid_0"
func addThisUserIdToFriendsNode() {
    let usersRef = self.ref.child("users") //the general users node
    let thisUserRef = usersRef.child(self.thisUserId) //this users node
    let thisUserFriends = thisUserRef.child("friends") //this users list of friends

    //load in all of this users friends
    thisUserFriends.observeSingleEvent(of: .value, with: { snapshot in
        let allOfThisUsersFriends = snapshot.children.allObjects as! [DataSnapshot]
        for user in allOfThisUsersFriends {
            let friendRef = usersRef.child(user.key) //the friend ref
            let friendsFriendRef = friendRef.child("friends") //a friend friends child node
            let nodeToAdd = friendsFriendRef.child(self.thisUserId) //add this uid
            nodeToAdd.setValue(true)
        }
    })
}

and the result

users
   uid_0
      name: "Larry"
      friends:
         uid_1: true
         uid_2: true
   uid_1
       name: "Moe"
       friends
          uid_0: true
   uid_2
       name: "Curly"
       friends
          uid_0: true



回答2:


If i understood your question right, i think, you can try to use Cloud DataStore instead of RealtimeDB. Difference description between this data bases you can find here.

Another way - use Firebase Functions.



来源:https://stackoverflow.com/questions/54909910/i-want-to-take-the-currentusers-userid-and-add-it-as-a-child-to-all-their-frien

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!