How to Use URLSession in Swift for Network Requests
Use
URLSession in Swift to create and manage network requests asynchronously. You create a URLSessionDataTask with a URL, start it with resume(), and handle the response in a completion handler.Syntax
The basic syntax for using URLSession involves creating a URLSessionDataTask with a URL and a completion handler. You then start the task with resume(). The completion handler provides the data, response, and error from the network call.
- URLSession.shared: A shared singleton session for simple tasks.
- dataTask(with:completionHandler:): Creates a task to fetch data from a URL.
- resume(): Starts the network task.
swift
let url = URL(string: "https://example.com")! let task = URLSession.shared.dataTask(with: url) { data, response, error in // Handle response here } task.resume()
Example
This example fetches JSON data from a URL and prints the result or error. It demonstrates how to create a data task, start it, and handle the asynchronous response.
swift
import Foundation let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") return } guard let data = data else { print("No data received") return } if let jsonString = String(data: data, encoding: .utf8) { print("Response JSON: \(jsonString)") } } task.resume() // Keep the playground running to wait for async response (only needed in playgrounds)
Output
Response JSON: {"userId":1,"id":1,"title":"delectus aut autem","completed":false}
Common Pitfalls
Common mistakes when using URLSession include:
- Forgetting to call
resume()on the task, so the request never starts. - Not handling errors or checking if data is nil.
- Trying to update UI directly inside the completion handler without dispatching to the main thread.
- Not validating the HTTP response status code.
swift
let url = URL(string: "https://example.com")! let task = URLSession.shared.dataTask(with: url) { data, response, error in // Wrong: Missing resume() means request never starts } // Correct usage: let correctTask = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("Invalid response") return } guard let data = data else { print("No data") return } DispatchQueue.main.async { // Update UI here } } correctTask.resume()
Quick Reference
Here are quick tips for using URLSession effectively:
- Always call
resume()on your task. - Check for errors and validate the HTTP response code.
- Use
DispatchQueue.main.asyncto update UI after network calls. - Use
URLSession.sharedfor simple requests or create custom sessions for advanced needs.
Key Takeaways
Always call resume() on your URLSessionDataTask to start the request.
Handle errors and check that data is not nil before using it.
Validate HTTP response status codes to ensure successful requests.
Update UI only on the main thread after receiving data.
Use URLSession.shared for simple network calls.