Make HTTP Request in Swift


In this tutorial, I am going to show you how to make an HTTP request in Swift and fetch data from the URL. There are multiple ways to perform this task. But in this tutorial, we will focus in two different ways.

Using URLSession class

Apple provides us with the URLSession class to work with network requests, downloading data in background data, checking network status and so on.

Below is the given Swift program that shows you how to make an HTTP request using the URLSession class:

import Foundation

let url = URL(string: "https://dummyjson.com/products/1")!

URLSession.shared.dataTask(with: url) {(data, res, error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8)!)
}.resume()

Using NSURLConnection class

You can also do this task using the NSURLConnection class. But Apple doesn’t recommend it as this class is considered legacy. It is better to use the URLSession class that I have just mentioned above.

Below is the code where you can see making an HTTP request using the NSURLConnection class:

import Foundation

let url = URL(string: "https://dummyjson.com/products/1")!
var req = URLRequest(url: url)

NSURLConnection.sendAsynchronousRequest(req, queue: OperationQueue.main) {(resp, data, error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8)!)
}