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()
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?