BlakeH
BlakeH

Reputation: 685

Swift - Wait until a Function is Completed

I have a application that requires a person to login for them to gain access. To do this i created a API to retrieve and store data from a database. For example, i created one to check and see if the username and password inputed is correct. The only problem though, is that the function that i use to retrieve the data is slow. It does not return the data in time for the checking system, to see if the username and password is correct.

class LoginViewController: UIViewController {

var statusCode = Int()
var returnedName = String()

@IBOutlet var usernameField: UITextField
@IBOutlet var passwordField: UITextField

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

    @IBAction func loginAction(sender: AnyObject) {

    var invalidLoginAlert = UIAlertView(title: "Invalid Username/Password", message: "Please input a correct Username or Password", delegate: nil, cancelButtonTitle: "Dismiss")

    var noInfoLoginAlert = UIAlertView(title: "Invalid Username/Password", message: "Please input a Username and Password to Proceed", delegate: nil, cancelButtonTitle: "Dismiss")

    usernameField.resignFirstResponder()
    passwordField.resignFirstResponder()

    if usernameField.text != "" && passwordField.text != "" {
        login(usernameField.text.lowercaseString, password: passwordField.text.lowercaseString)
        sleep(2)
        if statusCode == 300 {
            println("Login Success")
            let MainView = self.storyboard.instantiateViewControllerWithIdentifier("MainView") as MainViewController
            self.presentViewController(MainView, animated: true, completion: nil)
        }
        else {
            invalidLoginAlert.show()
            println("Login Failed")
        }
    }
    else {
        noInfoLoginAlert.show()
        println("Cannot Login, Invalid Information")
    }
}

As you see above, i have to use the sleep() function in order to slow down the function. This does not work always, because the connection is slower in different places (may take longer than 2 seconds to load) EX - 3G and LTE or slow WiFi.

The function Login(username: string, password: string), returns a code determining if the username and password is correct. If they are both correct, it will return the code 300, if not it will return 400.

Is there a way that i could could create a didFinishLoading() function, returning a bool, to check and see if the information from the login() function is loaded? this way it will not matter if their connection is slow.

Blake

EDIT: Here is my Networking Code:

func login(username: String, password: String){

    // Now escape anything else that isn't URL-friendly
    var usernameID = username.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    var passwordID = password.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    var urlPath = "http://www.example.com"
    var url: NSURL = NSURL(string: urlPath)
    var session = NSURLSession.sharedSession()
    var task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        var err: NSError?
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary

        var name: String? = jsonResult["data"] as String?;
        var code: Int = jsonResult["status"] as Int;

        self.statusCode = code
        println(self.statusCode)
        })
    task.resume()
}

Upvotes: 2

Views: 6243

Answers (1)

Mundi
Mundi

Reputation: 80265

In your completion handler - where you are computing jsonResult - that is where you should notify your view controller that username and password have or have not been received.

Upvotes: 1

Related Questions