qstatus/qStatus/Utilities/NetworkSupport.swift
2026-03-03 19:37:18 +01:00

40 lines
1.5 KiB
Swift

import Foundation
enum NetworkSupport {
static func data(for request: URLRequest, context: String) async throws -> (Data, HTTPURLResponse) {
do {
let (data, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse else {
throw PostingError(message: "\(context): invalid server response.")
}
return (data, http)
} catch let error as PostingError {
throw error
} catch let error as URLError {
throw PostingError(message: "\(context): \(networkMessage(for: error.code))")
} catch {
throw PostingError(message: "\(context): \(error.localizedDescription)")
}
}
static func responseBody(_ data: Data) -> String {
let body = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return body.isEmpty ? "Empty response body" : body
}
private static func networkMessage(for code: URLError.Code) -> String {
switch code {
case .notConnectedToInternet:
return "No internet connection."
case .timedOut:
return "Request timed out."
case .cannotFindHost, .cannotConnectToHost:
return "Cannot connect to host."
case .secureConnectionFailed:
return "TLS/SSL connection failed."
default:
return "Network error (\(code.rawValue))."
}
}
}