How to return an outer function inside an asynchronous inner function in swift?

I am creating a swift class which contain of a function which validate if the user is true. However, the userVerifyResult will always return “false” even if the result is true due to dataTaskWithRequest function is executed asynchronously. How can I get around with that?

class userLibService: NSObject{

   func VerifyUser() -> String{
         var userVerifyResult = "false"
        var url =  NSURL(string: "")!
        var request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"

        var bodyData = "username=tee&password=123&data=true"

        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){

            data, response, error in

            var parseError: NSError?

            if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as? [String : String] {

                 if(json["valid"]! == "true"){
                    userVerifyResult = "true"
                    userVerifyResult = "false"





        return userVerifyResult

In my main program:

  • IOS UIMenuController UIMenuItem, how to determine item selected with generic selector method
  • applicationMusicPlayer volume notification
  • Linker command failed with exit code 1 error in Xcode project
  • Xcode: project navigator, difference between Yellow folder and blue folder
  • Keyboard Extension Crash on Device
  • Mix Objective-C and C++ and OpenCV
  • var test = userLibService()

    and it will return “false” even the username and password is true

    2 Solutions Collect From Internet About “How to return an outer function inside an asynchronous inner function in swift?”

    Use completion handler, as Apple does in their frameworks:

    func verifyUser(completionHandler: ((result: Bool)->())) {

    then return the result via

            if(json["valid"]! == "true"){
                completionHandler(result: true)
                completionHandler(result: false)

    then invoke it as

    verifyUser { (result) -> () in

    There is no way to block a NSURLSessionDataTask (that i know of) until you return the function, so its not possible to do it like that. You will have to have a callback in your tasks completion handler that will print the result or delegate the printing to another function