My function always returns false the first time

ZbadhabitZ

This may be a bit of an obscure question, but I cannot seem to figure out what is happening here. I have a "login" function that checks a username and password against an API. For some reason, calling this function returns false the first time, but if I call the function a second time, it returns the proper true, assuming I enter the correct credentials.

Here is the function:

if testLogin(usernameTextField.text!, password: passwordTextField.text!) {
            performSegueWithIdentifier("dismissLogin", sender: self)
        } else {
            let alert = UIAlertView()
            alert.title = "Login Problem"
            alert.message = "Wrong username or password."
            alert.addButtonWithTitle("Dismiss")
            alert.show()
        }
    }

The testLogin function appears here;

func testLogin(username: String, password: String) -> Bool {

    let jsonString = "{\"username\":\"\(username)\",\"password\":\"\(password)\"}"
    let myURL = "http://myurl.com/api/login.php"

    let url:NSURL = NSURL(string: myURL)!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        do {
            let json:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

            if let result = json as? [String: AnyObject] {
                if let status = result["Status"] as! Int? {
                    if status == 200 {
                        self.loginCheck = true
                    } else {
                        self.loginCheck = false
                    }
                }
            }
        } catch {
            print(error)
        }            
    }   
    task.resume()
    return loginCheck
}

Sorry for the length. I can't seem to fathom, though, why calling testLogin the first time returns false, but calling it the second time returns true. Almost as if the function is not calling the website fast enough and is returning false, but the second time I call the function, it has had time to check the website?

Vladimir

Your method testLogin is incorrect. Method dataTaskWithRequest is asynchronous. You need to create two callbacks success and failure (closures). Which will be called if request completes. Look at this https://github.com/Alamofire/Alamofire.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

my function in jquery that is testing if the mouse is down always returns false

Recursive Function Always Returns False

My method always returns false but it works

React tetris. Function always returns false

in_array function always returns false

JS Checking return function with if, always returns false

Why does my function always returns false, even if it finds return true before?

Boolean returns false first time in activity

Logical in my R function always returns "TRUE"

My function returns a string but comparison is always wrong

My file exists though fileExistsAtPath always returns false

My check for whether a graph is a Binary Tree always returns false

isAssignableFrom always returns false

Contains always returns false

isEqualToString always returns False

hasNextLine() always returns false

isHardwareAccelerated() always returns false

Always returns false

StrPos always returns False?

PeekMessage always returns FALSE

Setting up passport for the first time. isAuthenticated() always returning false

PHP is_writable() function always returns false for a writable directory

How to ensure that a stored function always returns TRUE or FALSE?

JS / JSX function always returns true even if it's false

React - Check if function returns true but always runs code for false

Why my encrypt algorithm always returns same salt every time?

Function returning always false when using a Boolean on my statement

Why does my getColor function always return false?

My Binary Search Algorithm Template Function is Always Returning False