Skip to content
DeveloperMemos

Making HTTP Requests with URLSession

iOS, Swift, URLSession, HTTP Request1 min read

When building an iOS app that interacts with a web server, it's common to need to make HTTP requests. In Swift, you can use the URLSession API to create and manage network requests. In this article, we'll explore how to use URLSession to make HTTP requests, including examples for making GET and POST requests.

Creating a URLSession

Before you can make a request, you'll need to create a URLSession. A URLSession manages the network requests and provides a way to configure things like timeout intervals and caching policies. Here's how to create a default URLSession:

1let session = URLSession.shared

You can also create a custom URLSession with a specific configuration:

1let config = URLSessionConfiguration.default
2let session = URLSession(configuration: config)

Making a GET Request

To make a GET request, you'll need to create a URL and a URLRequest. The URL is the address of the resource you want to request, and the URLRequest is an object that represents the request.

1if let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") {
2 var request = URLRequest(url: url)
3 request.httpMethod = "GET"
4
5 let task = session.dataTask(with: request) { data, response, error in
6 if let error = error {
7 print("Error: \(error.localizedDescription)")
8 } else if let data = data {
9 // Handle response data
10 }
11 }
12
13 task.resume()
14}

In this example, we're making a GET request to the JSONPlaceholder API to retrieve a todo item with an ID of 1. We create a URL object from the string, then create a URLRequest object with a httpMethod of "GET". We then create a URLSessionDataTask with the request and a completion handler that will be called when the request completes.

Making a POST Request

To make a POST request, you'll need to include the request body in the URLRequest. Here's an example of making a POST request to create a new todo item on the server:

1if let url = URL(string: "https://jsonplaceholder.typicode.com/todos") {
2 var request = URLRequest(url: url)
3 request.httpMethod = "POST"
4
5 let newTodo = ["title": "Buy groceries", "completed": false]
6 let jsonData = try? JSONSerialization.data(withJSONObject: newTodo)
7
8 request.httpBody = jsonData
9 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
10
11 let task = session.dataTask(with: request) { data, response, error in
12 if let error = error {
13 print("Error: \(error.localizedDescription)")
14 } else if let data = data {
15 // Handle response data
16 }
17 }
18
19 task.resume()
20}

In this example, we're creating a new todo item by making a POST request to the JSONPlaceholder API. We create a URLRequest object with a httpMethod of "POST", then create a dictionary representing the new todo item and convert it to JSON data using the JSONSerialization API. We then set the httpBody of the request to the JSON data and set the "Content-Type" header field to "application/json". Finally, we create a URLSessionDataTask with the request and a completion handler that will be called when the request completes.

Conclusion

In this article, we've explored how to use URLSession to make HTTP requests in Swift, including examples for making GET and POST requests. URLSession provides a powerful and flexible API for managing network requests in your iOS app. With this knowledge, you can now build apps that interact with web servers and consume RESTful APIs.