0

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
        }
    }
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
James
  • 1,088
  • 3
  • 11
  • 29
  • you can't wait for an async method to finish before returning the result. Do whatever you need to do inside the completion handler – Leo Dabus Dec 02 '15 at 21:03
  • @LeoDabus Oh, okay. So you can't return a value from an async method, you've got to do everything inside the closure? – James Dec 02 '15 at 21:04
  • 2
    If your code would wait for an async method it wouldn't be async – Leo Dabus Dec 02 '15 at 21:05
  • that made me laugh leo haha – Hayden Holligan Dec 02 '15 at 21:06
  • @LeoDabus Haha, okay I've self-referred myself here. http://stackoverflow.com/a/4560233/3033149 – James Dec 02 '15 at 21:09
  • @LeoDabus, you should post your comment as an answer so James can accept it. I was getting ready to post the same thing as an answer when I noticed your comment. – Duncan C Dec 02 '15 at 21:44
  • @DuncanC feel free to post it if you would like to. We can also close it as duplicate. – Leo Dabus Dec 02 '15 at 21:45
  • I'm curious as to why this question has acquired a downvote. I understand Stackoverflow as a place to go if you don't understand something, and downvotes are to be used if the question itself is presented or conveyed badly. Do correct me if I'm wrong. – James Dec 02 '15 at 23:07

0 Answers0