Reputation: 4408
I want to get list of users from firebase, I am following a tutorial which is not using swift 5, but I am writing my code in swift 5. I am pretty new to swift and iOS development. How can I convert the following code to swift 5
I have a users in firebase database which ~I am trying to retrieve, and each user has email
and name
User
class User: NSObject {
var name: String?
var email: String?
}
Trying to convert below code to swift 5
FIRDatabase.database().reference().child(“users”).observeEventType(.ChildAdded, withBlock: { (snapshot) in
If let dictionary = snapshot.value as? [String: AnyObject] {
}
}, withCancelBlock: nil)
This is what I have done, and I don't think I am getting the data right
func fetchUsers() {
Database.database().reference().child("users").observe(.childAdded) { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.setValuesForKeys(dictionary) // this is where my error is
}
}
}
Error
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FBCHSRM.User 0x600002701050> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key email.'
Data in the dictionary looks like this
Upvotes: 0
Views: 921
Reputation: 247
you are setting values wrongly you should change something. first add your user struct
init(email: String, username: String) {
self.email= email
self.name = name
}
then make an array of users to store data as:
var users:[User] = []
in fetchUser func
if let dictionary = snapshot.value as? [String: AnyObject] {
for dic in dictionary{
let emailFromFB = dic["email"] as? String ?? ""
let username = dic["username"] as? String ?? "" /
var u: User(email: email, name:name)
users.append(u)
}
}
print(users)
Upvotes: 1