4

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

2 Answers 2

6

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.