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

为君一笑 提交于 2019-12-01 20:46:13

问题


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



来源:https://stackoverflow.com/questions/32347817/how-to-return-an-outer-function-inside-an-asynchronous-inner-function-in-swift

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