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.
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")")
}
}
}
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?