How to create and send the json data to server using swift language

Uday picture Uday · Dec 26, 2014 · Viewed 32.5k times · Source

I'm new to IOS development and I have started with the swift language.

I'm trying to get the value from two text fields and convert those two text fields into json and send that json to the server receive.php.

lets concider that tow text fields are - name - pass

how do i create a Json & send that to server when a button is clicked ?

Answer

Suhit Patil picture Suhit Patil · Dec 26, 2014

By using http POST method with NSURLSession. Let's say you are calling submitAction method on the press of the login button

Swift 3

@IBAction func submitAction(_ sender: UIButton) {

    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid

    let parameters: [String: String] = ["name": nametextField.text, "password": passwordTextField.text]

    //create the url with URL
    let url = URL(string: "http://myServerName.com/api")! //change the url

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }

        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}