Morgane Flamant Morgane Flamant - 1 month ago 9
Swift Question

Login Connection, method Get swift with API

I want to connect in an app in swift 2.1
I have a button logIn and I make a function loginButton.
I want to recover my url: localhost/connexion/login/password
And with that I want to say if the user is in the database it's ok !
But I don't really anderstant swift, I'm a beginner in this language.
So there is my code:

@IBAction func loginButton(sender: AnyObject) {
NSLog("login ok")
let _login = loginText.text
let _password = passwordText.text

if(_login!.isEmpty || _password!.isEmpty){
var alert:UIAlertView = UIAlertView()
alert.title = "Error"
alert.message = "Entrez vos identifiants"
alert.delegate = self
alert.addButtonWithTitle("OK")
alert.show()
} else{
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/connexion/"+_login!+"/"+_password!)!)
request.HTTPMethod = "GET"
let postString = "login=\(_login!)&pass=\(_password)"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request)
task.resume();
}
}


I have follow this before How to make an HTTP request in Swift?
but it doesn't work.
I tried a lot of things, but without really understand what happened and I don't find a great tutorial with very good explanation. If someone can explain me how to do it I will be very happy !

Answer

I think for sending data to server you should create a "POST" request and use NSURLSession API to send data

@IBAction func loginButton(sender: AnyObject) {
        NSLog("login ok")
        let _login = loginText.text
        let _password = passwordText.text

        if(_login.isEmpty || _password.isEmpty){
            var alert:UIAlertView = UIAlertView()
            alert.title = "Error"
            alert.message = "Entrez vos identifiants"
            alert.delegate = self
            alert.addButtonWithTitle("OK")
            alert.show()
        } else{
            let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/connexion/login")!)
        request.HTTPMethod = "POST"
        let params = ["login": _login, "pass": _password]
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
            request.HTTPBody = data
        } catch let error as NSError {
            print("json error: \(error.localizedDescription)")
        }

        let loginTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
            guard let data = data, let _ = response  where error == nil else {
                print("error")
                return
            }

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
                print(json)
            } catch let error as NSError {
                print("json error: \(error.localizedDescription)")
            }
        })
        loginTask.resume()
        }
    }

for using "GET" replace else part with

 let url = "http://localhost:8888/connexion/login=\(_login)&pass=\(_password)"
    let urlString = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    let request = NSURLRequest(URL: NSURL(string: urlString)!)

    let loginTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in

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

        /*do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
            print(json)
        } catch let error as NSError {
            print("json error: \(error.localizedDescription)")
        }*/
    if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
      print("statusCode should be 200, but is \(httpStatus.statusCode)")
      print("response = \(response)")
    }

    let responseString = String(data: data!, encoding:NSUTF8StringEncoding)
    print("responseString = \(responseString)")
    })
    loginTask.resume()
Comments