How to use completion handler correctly [duplicate]

百般思念 提交于 2019-12-12 03:56:13

问题


I understand how completion handlers work, but im a bit confused on the syntax. Below is a function that, given a username, calls a parse query to find out the corresponding userId. The query ends after the function is returned (so it returns nil), which is why we need the completion handler. How do i implement it?

func getUserIdFromUsername(username: String) -> String {
    var returnValue = String()
    let query = PFQuery(className: "_User")
    query.whereKey("username", equalTo: username)
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if let objects = objects {
            for object in objects {
                returnValue = object.objectId!
            }
        }
    }
    return returnValue

}

NOTE: I know examples similar to this exist, but they are either not swift, or extremely lengthy. This is a short and concise version that contains Parse.


回答1:


Here's how to implement it:

func getUserIdFromUsername(username: String, completionHandler: String -> Void) {

    let query = PFQuery(className: "_User")
    query.whereKey("username", equalTo: username)
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if let objects = objects {
            for object in objects {
                completionHandler(object.objectId!)
            }
        }
    }
}

And here's how to use it:

getUserIdFromUsername("myUser") { id in
    doSomethingWithId(id)
}


来源:https://stackoverflow.com/questions/35152508/how-to-use-completion-handler-correctly

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