Retrieve String value from function with closure in Swift

社会主义新天地 提交于 2019-12-17 09:57:51

问题


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. However - since the firebase ObserveEvent is in closures, I can't return any value back because the actions happens asynchronous(?). I was wondering if it was a way of accomplishing this?

The function looks like this:

func GetUsername(uid:String) -> String {
    var username = String()
    firebase.child("Users").child(uid).observeSingleEventOfType(.Value) { (snapshot:FIRDataSnapshot) in

        username = snapshot.value!["Username"] as! String

    }

    return username
}

Obviously this doesn't work, but I want to be able to get the data by doing a GetUsername("whatevertheidmightbe"). Ideas?


回答1:


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")
    }
}


来源:https://stackoverflow.com/questions/38409338/retrieve-string-value-from-function-with-closure-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!