How do I handle errors and retries with URLSession in Swift?

Handling errors and implementing retries with URLSession in Swift is crucial for creating robust network calls. When dealing with network requests, it's common to encounter various errors, such as timeouts, request failures, or server errors. To improve user experience, you can implement a retry mechanism to automatically attempt the request again under certain conditions.

Example

import Foundation class NetworkManager { let session = URLSession.shared func fetchData(from url: URL, retries: Int = 3, completion: @escaping (Data?, Error?) -> Void) { var attempt = 0 let task = { self.session.dataTask(with: url) { data, response, error in if let error = error { if attempt < retries { print("Attempt \(attempt + 1) failed: \(error). Retrying...") attempt += 1 self.fetchData(from: url, retries: retries, completion: completion) } else { print("Failed after \(attempt) attempts.") completion(nil, error) } return } completion(data, nil) }.resume() } task() } } // Usage example: let manager = NetworkManager() if let url = URL(string: "https://api.example.com/data") { manager.fetchData(from: url) { data, error in if let data = data { print("Data received: \(data)") } else { print("Error occurred: \(error?.localizedDescription ?? "Unknown error")") } } }

urlsession swift error handling retry mechanism network requests