Fetch and decode JSON with async/await and URLSession
WHAT IT TESTS: modern networking basics. OUTLINE: call URLSession.shared.data(from:) inside an async throws function, check the HTTPURLResponse status, then JSONDecoder().decode([User].self) and let errors propagate via try.
WHAT IT TESTS: whether you can write clean modern async networking with proper error handling. ANSWER OUTLINE: mark the function async throws, await URLSession.shared.data(from: url) which returns data and a response, cast the response to HTTPURLResponse and verify the status code is in 200..<300 throwing otherwise, then decode with JSONDecoder into [User] where User conforms to Codable, letting transport and decoding errors propagate through try for the caller to catch.
Read the original → interview
- #ios
- #swift
- #async-await
- #urlsession
- #codable
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.