Structuring a networking layer in Swift using async/await can simplify your code and make it more readable. Below is an example of how you can set up a basic networking layer with async/await for making GET requests.
import Foundation
struct NetworkError: Error {
let message: String
}
class NetworkService {
static let shared = NetworkService()
private init() {}
func fetchData(from urlString: String) async throws -> Data {
guard let url = URL(string: urlString) else {
throw NetworkError(message: "Invalid URL")
}
let (data, response) = try await URLSession.shared.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
throw NetworkError(message: "Server error")
}
return data
}
}
// Usage
Task {
do {
let data = try await NetworkService.shared.fetchData(from: "https://api.example.com/data")
// Process the data
} catch {
print("Error: \(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?