In my Firebase Realtime Database, I have a node labelled "groups" and this is how I constructed it:
Underneath the "users" above, I'm trying to use those userIds to reference the data within each user. This is how I constructed each "users" node I'm trying to reference:
In the below code snippet, I get the userIds from a snapshot of the groups' users child node. And then I run a for-in loop on those userIds to access the information in the "users" node.
The print("This should be the individual userId: ", userId) statement prints out each userId correctly. And the userRef.observeSingleEvent(of: .value, with: { (snapshot) in gets called the first time the for-in loop is called, but it's almost like it's ignored. The app crashes because the user array comes up empty at the end. However, a ridiculous amount of empty users show up in the array (when looking at the Variables View in the Debug Area). So, i feel like I'm running some form of a redundant loop or something.
guard let groupChatPartnerId = message.chatPartnerId() else {
return
}
var users: [User]?
let ref = Database.database().reference().child("groups").child(groupChatPartnerId)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
let groupId = snapshot.key
let groupName = snapshot.childSnapshot(forPath: "groupName").value as! String
let userIdDictionary = snapshot.childSnapshot(forPath: "users").value as! Dictionary<String,AnyObject>
let userIds = Array(userIdDictionary.keys)
print("userIds: ", userIds)
for userId in userIds {
print("This should be the individual userId: ", userId)
let userRef = Database.database().reference().child("users").child(userId)
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
print("This is the snapshot: ", snapshot)
let email: String = snapshot.childSnapshot(forPath: "email").value as! String
print("user's email: ", email)
let uid = snapshot.key
let username = snapshot.childSnapshot(forPath: "username").value as! String
let profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String
let user = User(uid: uid, userUsername: username, userProfileImageUrl: profileImageUrl, userEmail: email)
users?.append(user)
print("user to append to users: ", user)
}, withCancel: nil)
}
print("users :", users)
let group = Group(groupId: groupId, groupName: groupName, users: users!)
self.showChatControllerForGroup(group: group)
}, withCancel: nil)
Let me know if you need any other information. Thanks in advance!

