我想使用currentUser的userId并将其作为孩子添加到他们所有朋友的数据中-使用Swift在Firebase中 [英] I want to take the currentUser's userId and add it as a child to all their friend's data- in Firebase with Swift

查看:62
本文介绍了我想使用currentUser的userId并将其作为孩子添加到他们所有朋友的数据中-使用Swift在Firebase中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Firebase数据库中,父数据是所有用户的userId.他们每个人都有一个child("friends"),其中包含所有朋友的userId的列表.

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.

我想获得每个currentUser朋友的userId,并将currentUseruserId添加到他们每个朋友的child("closeFriends")节点

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"

我希望"closeFriends"成为具有userId的节点,就像已经存在friends一样.

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]()

我尝试了这个for循环,但没有执行任何操作:

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)
        }
    }

作为参考,friendList是在另一个文件(我的"FriendSystem")中创建的朋友的列表.

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

我确定还有另一种方法来获取用户的所有朋友,然后运行循环以将currentUser添加到所有这些朋友的child("closeFriends")中,我只是无法弄清楚.

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!

推荐答案

我想获取每个currentUser的朋友的userId并添加 currentUser的每个朋友子级的userId("closeFriends") 节点

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"

这个想法是浏览这个用户(当前用户)的朋友列表,并将这个用户uid添加到其他用户的朋友列表中.在此示例中,我只是为每个用户创建一个朋友"节点,但您可以将其设为"closeFriends"或您想要的任何名称.

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.

这是执行此操作的代码

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)
        }
    })
}

和结果

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

这篇关于我想使用currentUser的userId并将其作为孩子添加到他们所有朋友的数据中-使用Swift在Firebase中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆