This question already has an answer here:
- How to return value from Alamofire 5 answers
I have a simple problem. I'm connecting to my RESTful server and trying to connect. I do get a response and everything works perfect, however when I try to call a function to set a variable, it just doesn't call it.
Code:
//
// LoginClass.swift
// LoginApp
//
// Created by Tarek Adel on 12/3/16.
// Copyright © 2016 Tarek Adel. All rights reserved.
//
import Foundation
import Alamofire;
import UIKit;
class LoginClass {
var result: Bool = false;
var username: String
var password: String
init(username: String, password:String) {
self.username = username;
self.password = password;
}
func login() -> Void {
let data = [
"grant_type" : "password",
"username" : self.username,
"password" : self.password,
"client_secret":"xxxxxx",
"client_id":"xxxxxx",
"scope": ""
]
Alamofire.request("http://localhost:8000/oauth/token", method: .post, parameters: data)
.responseJSON { response in
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 200:
self.loginSuccess();
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
}
func loginSuccess() {
self.result = true;
}
}
This is where I check the self.result
:
@IBAction func loginButton(_ sender: UIButton) {
let username = usernameTextField.text!;
let password = passwordTextField.text!;
let loginClass = LoginClass(username: username, password:password)
loginClass.login()
if(loginClass.result == true) {
resultLabel.text = "Correct!"
} else {
resultLabel.text = "Wrong Credentials"
}
}
You need to use completion handler with your
login
method because it is making an Async call, so make onecompletionHandler
with your login method and than execute that if condition inside thatcompletionHandler
.Now call this login method like this.
Note: If you want JSON response also then make completion handler with two parameter Bool and Dictionary and pass JSON also with that.