How do I structure a networking layer with async/await in Swift?

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.

Example Networking Layer

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

async await Swift networking URLSession data fetching Swift networking layer