public func getCountryAsync(stateManager: StateManager, onComplete: @escaping (_ info: NetworkInfo) -> Void, onError: @escaping (_ error: Error) -> Void) async {
let maxRetries = 2
let retryDelays: [TimeInterval] = [10, 15] // Seconds
for attempt in 0...maxRetries {
let startTime = Date()
let postfix = stateManager.getPostfix()
var url = URL(string: "https://tracker.cloudapps.casa/country")!
#if DEBUG
url = URL(string: "https://tracker.cloudapps.casa/country")!
#endif
Logger.shared.log("🌐 [Tracker] Начало запроса в \(startTime) \(postfix) (Attempt: \(attempt + 1))", level: .debug, category: .mainFlow)
var request = URLRequest(url: url)
request.timeoutInterval = 5 // ✅ Ставим таймаут 10 секунд
do {
let (data, response) = try await URLSession.shared.data(for: request)
let endTime = Date()
let elapsed = String(format: "%.2f", endTime.timeIntervalSince(startTime))
Logger.shared.log("⏱️ [Tracker] Ответ получен через \(elapsed) сек. \(postfix) (Attempt: \(attempt + 1))", level: .debug, category: .mainFlow)
if let httpResponse = response as? HTTPURLResponse,
!(200...299).contains(httpResponse.statusCode) {
let httpError = NSError(domain: "NetworkService", code: httpResponse.statusCode, userInfo: [
NSLocalizedDescriptionKey: "HTTP error \(httpResponse.statusCode)"
])
Logger.shared.log("❌ HTTP error: \(httpResponse.statusCode) (Attempt: \(attempt + 1))")
if attempt == maxRetries {
onError(httpError)
} else {
print("httpError: \(httpError)")
}
continue // Retry
}
do {
let location = try JSONDecoder().decode(NetworkInfo.self, from: data)
Logger.shared.log("⏱️ [Tracker] Location from tracker: ⦗ \(location.country) ⦘ (Attempt: \(attempt + 1))", level: .debug, category: .mainFlow)
DispatchQueue.main.async {
onComplete(location)
}
return // Success, exit the loop
} catch {
Logger.shared.log("❌ Decode error: \(error) (Attempt: \(attempt + 1))", level: .error)
if attempt == maxRetries {
onError(error)
} else {
print("Decode error: \(error)")
}
continue // Retry
}
} catch {
let endTime = Date()
let elapsed = String(format: "%.2f", endTime.timeIntervalSince(startTime))
Logger.shared.log("⏱️ [Tracker] Error received after \(elapsed) seconds. \(postfix) (Attempt: \(attempt + 1))", level: .debug, category: .mainFlow)
Logger.shared.logWithProps("Location", eventProperties: [
"Country": "request error",
"Error": error.localizedDescription,
"Source": "Tracker"
])
if attempt == maxRetries {
onError(error)
} else {
print("Network error: \(error)")
}
}
// Wait before retrying, unless it's the last attempt
if attempt < maxRetries {
let delay = retryDelays[attempt]
Logger.shared.log("⏱️ [Tracker] Retrying in \(delay) seconds", level: .debug, category: .mainFlow)
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) // Convert seconds to nanoseconds
}
}
}
This revised solution is a robust and reliable way to perform network requests with retries in Swift using async/await. It addresses the core issues of the original code and provides a clean, understandable implementation. Remember to replace myStateManager with your actual StateManager instance.