NetworkingMidOpen-ended
How does `URLSession` work?
Explanation & Code
Answer:
URLSession is Apple's networking API for HTTP requests. It manages connection pooling, caching, cookies, and authentication. You create tasks from it to perform requests.
Code Example:
// Modern async/await approach
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw NetworkError.badResponse
}
return try JSONDecoder().decode(User.self, from: data)
}
// POST request
func createUser(_ user: User) async throws {
var request = URLRequest(url: URL(string: "https://api.example.com/users")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(user)
let (_, response) = try await URLSession.shared.data(for: request)
// handle response
}
Rate your understanding: