swift - How to parse data from firebase and then save it within a model. Swift3 MVC format -
i have user class within firebasedb. expect flat file db like: users->uid->profile->key/values. trying implement best practice within code want data handled user model in xcode project. how go parsing data , saving class variables within model.
class user { private var _username: string private var _uid: string var uid: string { return _uid } var username: string { return _username } init (uid: string, username:string) { self._uid = uid self._username = username } func getuserdata() { dataservice.ds.ref_users.observesingleevent(of: .value, with: { (snapshot) in if let users = snapshot.value as? dictionary<string, any>{ (key, value) in users { // use in loop iterate through each key/value pair in database stored dictionary. if let dict = value as? dictionary<string, any> { // gets inside user id if let profile = dict["profile"] as? dictionary<string, any> { // gets inside profile if let username = profile["username"] as? string { self._uid = key // stores uid of user key. self._username = username } else { let username = profile["name"] as? string self._uid = key self._username = username! } } } } }
this trying lost how store data values within class. fyi: username attribute under profile.
you looping through entire list of users in database , assigning user properties repeatedly, overwriting value previous loop cycle.
in order correct user values assigned, need way of knowing correct path values. suggest saving users using assigned firebase uid.
if know correct uid can implement following code:
func getuserdata() { dataservice.ds.ref_users.child(_uid).child("profile").observesingleevent(of: .value, with: { (snapshot) in guard let profiledict = snapshot.value as? [string: any] else { print("error fetching user") return } self._username = profiledict["username"] as? string ?? profiledict["name"] as! string }) }
the way "username" force unwrapped in original code doesn't appear safe i'm assuming work out. otherwise following line should changed safely unwrap optional:
self._username = profiledict["username"] as? string ?? profiledict["name"] as! string
Comments
Post a Comment