0

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 !

Community
  • 1
  • 1
Kraven
  • 245
  • 1
  • 3
  • 16

1 Answers1

0

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()
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
  • I replaced the else by yours, but i have already try this and I have this error: – Kraven Oct 25 '16 at 10:47
  • json error: The data couldn’t be read because it isn’t in the correct format. – Kraven Oct 25 '16 at 10:47
  • I think your response for the login request is not coming in json format, check this link http://stackoverflow.com/questions/37825284/the-data-couldn-t-be-read-because-it-isn-t-in-the-correct-format – Suhit Patil Oct 25 '16 at 10:54
  • I have check but I don't understand. I return a son_encode in my API who send this: {"0":"5","1":"c@gmail.com","2":"blabla12","success":true} And I never call 'DidReceiveData'. And in my code I made a print(data) and is it this: Optional(<2020636f 6e6e6578 696f6e2e 2e2e7b22 30223a22 35222c22 31223a22 6340676d 61696c2e 636f6d22 2c223222 3a22626c 61626c61 3132222c 22737563 63657373 223a7472 75657d6d 6f742064 65207061 73736520 696e636f 72726563 746d6f74 20646520 70617373 6520696e 636f7272 6563746d 6f742064 65207061 73736520 6f6b4327 65737420 6f6b>) I really don't understand – Kraven Oct 25 '16 at 12:08