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