I use a design pattern MVC. I have model and controller. Model must get data from the database and send it to controller. I have such structure, for example, but it does not work:
Class of model
class AuthModel
{
func getDataFrom(request: NSMutableURLRequest, completion: (result: NSDictionary)->())
{
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if let data = data
{
let result = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
completion(result: result)
} else {
print(error?.localizedDescription)
}
}
task.resume()
}
func getUser(let username : String, let password : String) -> NSDictionary
{
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/together/auth.php")!)
request.HTTPMethod = "POST"
let postString = "user=\(username)&pass=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
var values : NSDictionary = ["":""]
getDataFrom(request) { (result) in
values = result
print(values["username"]) //output1
}
print(values["username"]) // output2
return values
}
}
Part of controller
@IBAction func LoginBtn(sender: AnyObject)
{
let values = authModel.getUser(usernameField.text!, password: passwordField.text!) as NSDictionary
}
Output1 shows me the value that I want, but output2 equals nil. Why? I guess it because of session and task. So maybe it does not want to return value? How should I change the code? I tried to cancel the task instead of resume it, but it led to the error.