I'm trying to send off login credentials to a GET
request via dataTaskWithURL()
, and then receiving a response back as a String. If the response is 401 Unauthorized
, then my function attemptLogin()
should return false
. Otherwise, it'll return true
.
At the moment this works, however only once loginButtonPressed(sender: AnyObject) is called twice does anything happen. Why could this be? I tried removing the dispatch_async()
as I thought this may be slowing things down however this was not the issue. Here's my code at the moment:
//
// LoginViewController.swift
// Login App
//
// Created by James Allison on 30/11/2015.
// Copyright © 2015 James Allison. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var pinField: UITextField!
@IBAction func loginButtonPressed(sender: AnyObject) {
submitLogin()
}
var loginResponse:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
}
func submitLogin() {
// first validate the fields
if usernameField.text! == "" || Int(pinField.text!) == 0 {
// empty
print("Fill in username & password.")
}
else {
if(attemptLogin(usernameField.text!, pin: pinField.text!)) {
print("YES!")
}
else {
print("NO!")
}
}
}
func attemptLogin(username: String, pin: String) -> Bool {
// construct url
let url = NSURL(string: "http://jamesallison.co/json.php?username=" + username + "&pin=" + pin)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
if let urlContent = data {
// convert to string
let dataString = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
// check if 401 or not
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if dataString == "401 Unauthorized\n" {
//print("incorrect login details")
self.loginResponse = false
}
else {
//print("correct login details!")
self.loginResponse = true
}
})
}
else {
// something failed
print("Error: invalid URL, no response or something.")
}
})
task.resume()
return self.loginResponse
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "loginSuccess") {
// upcoming is set to FirstViewController (.swift)
//let upcoming: FirstViewController = segue.destinationViewController as! FirstViewController
}
}
}