В моей базе данных Firebase родительскими данными являются все userId
s пользователей.У каждого из них есть child("friends")
, который содержит список всех их друзей * userId
s.
Я хочу получить userId
друзей каждого currentUser
друзей и добавить currentUser
's userId
для каждого из узлов child("closeFriends")
их друзей
Вот так выглядит моя структура данных:
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
s точно так же, как friends
уже.
Это мои справочные переменные и функции:
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
, но ничего не сделал:
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").
Я уверен, что есть еще один способ получить всех друзей пользователя, а затем запуститьЦикл, чтобы добавить currentUser
ко всем этим друзьям child("closeFriends")
, я просто не смог разобраться.
Супер застрял на этом, надеюсь, вы можете помочь!Спасибо!