ios - (Firebase) Assign value to global variable from a returned completion handler function -
i have function retrieves "users" node of firebase database, , trying assign global variable equal number of users in "users" node so:
func getusers(completionhandler:@escaping (int) -> ()) { let ref = database.database().reference().child("users") ref.observe(.childadded, with: { (snapshot) in if let dictionary = snapshot.value as? [string: anyobject] { let user = user() user.id = snapshot.key user.setvaluesforkeys(dictionary) self.users.append(user) completionhandler(self.users.count) } }, withcancel: nil) }
then, in viewdidload() function, try assign global variable equal number of users in "users" node this:
var usercount: int? override func viewdidload() { super.viewdidload() getusers(){ (count) in self.usercount = count } print(usercount) }
this prints nil, , should 12, amount of users added firebase database. since unfamiliar completion handlers, unsure how fix this.
any , appreciated.
your completion closure @escaping
async reason print(usercount)
executed before completion block returns , getting nil
. try this:
var usercount: int? override func viewdidload() { super.viewdidload() getusers(){ (count) in self.usercount = count print(self.usercount) } }
or can remove @escaping
, make completion closure sync.
func getusers(completionhandler:(int) -> ()) { let ref = database.database().reference().child("users") ref.observe(.childadded, with: { (snapshot) in if let dictionary = snapshot.value as? [string: anyobject] { let user = user() user.id = snapshot.key user.setvaluesforkeys(dictionary) self.users.append(user) completionhandler(self.users.count) } }, withcancel: nil) }
Comments
Post a Comment