How to return an outer function inside an asynchro

2019-02-25 11:09发布

问题:

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: "http://www.example.com/test.php")!
        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"
                 }else{
                    userVerifyResult = "false"

                }

            }



        }

         task.resume()

        return userVerifyResult
    }
}

In my main program:

var test = userLibService()
  println(test.VerifyUser())

and it will return "false" even the username and password is true

回答1:

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)
        }else{
            completionHandler(result: false)
        }

then invoke it as

verifyUser { (result) -> () in
    println(result)
}


回答2:

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