Fetching JSON with URLSession
Spot the common mistake that stops a URLSession request from ever running.
Codeswift
struct User: Decodable { let id: Int; let name: String }
func fetchUser() {
let url = URL(string: "https://api.example.com/user/1")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
if let http = response as? HTTPURLResponse, http.statusCode == 200 {
let user = try? JSONDecoder().decode(User.self, from: data)
print(user?.name ?? "No name")
}
}
}Why does this code never print anything or hit the network?