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

Handling timeouts and retries is essential when working with URLSession in Swift, especially when making network requests that may fail due to various reasons like connectivity issues or server unavailability. Below is an example of how to implement timeout and retry logic with URLSession.

let url = URL(string: "https://api.example.com/data")! var attempts = 0 let maxAttempts = 3 func fetchData() { let session = URLSession(configuration: .default) var request = URLRequest(url: url) request.timeoutInterval = 10.0 // Timeout after 10 seconds let task = session.dataTask(with: request) { (data, response, error) in if let error = error { print("Request failed with error: \(error)") attempts += 1 if attempts < maxAttempts { print("Retrying... Attempt \(attempts + 1) of \(maxAttempts)") fetchData() } else { print("Max attempts reached. Giving up.") } } else { print("Data received: \(data!)") // Process the received data } } task.resume() } fetchData()

timeout retries URLSession Swift network requests handling errors