How do I perform GET and POST requests in Swift?

Nathan McKaskle picture Nathan McKaskle · Jun 26, 2015 · Viewed 14.8k times · Source

I adapted this from Ray Wenderlich's iOS Apprentice tutorial part 4.

This code works as a GET request sent to my Strongloop API with a simple database model, however:

  1. This works, but I don't know why it works, since it invokes no method that I can see to actually send the request.

  2. I see no means to make it into a POST request.

My question is: How do I perform a POST request? Is it done in a completely different way?

Let me know if you need more information.

    class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func getFromDB() {
        let url = urlWithSearchText("")
        println("URL: '\(url)'")
        if let jsonString = performGetRequestWithURL(url) {
            println("Received JSON string '\(jsonString)'")
        }
    }


    func urlWithSearchText(searchText: String) -> NSURL {
        let escapedSearchText = searchText.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        let urlString = String(format: "http://localhost:3000/api/Tests", escapedSearchText)
        let url = NSURL(string: urlString)
        return url!
    }    

    func performGetRequestWithURL(url: NSURL) -> String? {
        var error: NSError?
        if let resultString = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error) {
            return resultString
        } else if let error = error {
            println("Download Error: \(error)")
        } else {
            println("Unknown Download Error")
        }
        return nil
    }

Here is a picture of this working:

https://dl.dropboxusercontent.com/u/14464971/Images/Messages%20Image%281477993527%29.png

Answer

Suhit Patil picture Suhit Patil · Dec 11, 2016

Swift 3 & above

GET

private func httpRequest() {

    //create the url with NSURL
    let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url

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

    //now create the URLRequest object using the url object
    let request = URLRequest(url: url)

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, 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)
            }
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}

POST

@IBAction func submitAction(sender: AnyObject) {

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

    let parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>

    //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 as URLRequest, 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()
}