I want to implement a friendsystem. Currently I am adding friends like this:
public func addFriends(emailUser:String, emailFriend:String, completion: @escaping (Bool) -> Void) {
let db = Firestore.firestore()
if emailFriend == "" {
print ("Failed to add friend")
completion(false)
}else {
getUserData(email: emailFriend, isForFriend: true) { success in
if success {
db.collection("users").document(emailUser).setData([
"friends" : [[self.userDataOfMyFriends!.email]:[self.userDataOfMyFriends!.uid]]
], merge: true)
completion(true)
}else{
print ("Failed to add friend")
completion(false)
}
}
}
}
The Firebase data structure of the user looks like this:
email
- "[email protected]"
friends
- 0
- "[email protected]": "AbCdeF1234567" // email:UID
uid
- "AbCdeF1234567" //current users UID
And I am loading the profile data including friends of the current user like this:
public func getUserData(email:String, isForFriend:Bool, completion: @escaping (Bool) -> Void) {
let db = Firestore.firestore()
let docRef = db.collection("users").document(email)
print (email)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let userEmail = document.get("email") as? String
let userUID = document.get("uid") as? String
let userFriends = document.get("friends") as? [[String:String]] // Here might be the problem
if isForFriend {
self.userDataOfMyFriends = UserData(email: userEmail, uid: userUID, friends: userFriends)
} else {
self.userData = UserData(email: userEmail, uid: userUID, friends: userFriends)
}
print("userdata geladen")
print (self.userData)
completion(true)
} else {
completion(false)
}
}
}
My UserDataModel looks like this:
public struct UserData {
var email:String?
var uid:String?
var friends:[[String:String]]?
}
But the result is always nil. How do I get the "map" data from Firebase in my UserDataModel?
CodePudding user response:
So you need
let userFriends = document.get("friends") as? [String:String]
As friends
is a dictionary not an array , hence
var friends:[String:String]?