Retrieve String value from function with closure in Swift

后端 未结 1 1214
生来不讨喜
生来不讨喜 2020-12-06 21:49

I am trying to retrieve a string value from Firebase in order to get each username with an unique UID that is passed to the function, which returns the username of the user.

相关标签:
1条回答
  • 2020-12-06 22:22

    You need to create completion handler like this

    func GetUsername(uid:String , completion: (String) -> ()) {
        firebase.child("Users").child(uid).observeSingleEventOfType(.Value) { (snapshot:FIRDataSnapshot) in
        if let username = snapshot.value!["Username"] as? String
            completion(username)
        }
        else {
            completion("")
        }
    }
    

    And call function like this way

    self.GetUsername(str) { (name) -> () in
        if name.characters.count > 0 {
             print(name)
        }
        else {
             print("Not found")
        }
    }
    
    0 讨论(0)
提交回复
热议问题