Learn how to:
- Call APIs using
async/await - Understand when to use
Codable(JSON) - Understand when to use direct URLs (images/files)
- Display API data in UI (Text and Image)
- Handle nested JSON responses
Always open the API in a browser before coding.
Example:
{ "quote": "Hello world" }You need to:
- Create a
struct - Decode using
Codable
Example:
https://robohash.org/hello
You will directly get an image or file.
You do not need:
- Struct
- Decoding
You just use the URL.
For JSON APIs:
- Create URL
- Fetch data
- Decode JSON
- Use result
Match your struct to the JSON:
struct Model: Codable {
let key: String
}let url = URL(string: "YOUR_API_URL")This is your API endpoint.
guard let url = URL(string: "YOUR_API_URL") else {
return nil
}Ensures URL is valid.
let (data, _) = try await URLSession.shared.data(from: url)- Sends request
- Waits for response
- Returns data
let result = try JSONDecoder().decode(Model.self, from: data)- Converts JSON → Swift object
do {
// network + decoding
} catch {
print("Error:", error)
}func fetchData() async -> Model? {
guard let url = URL(string: "YOUR_API_URL") else {
return nil
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
let result = try JSONDecoder().decode(Model.self, from: data)
return result
} catch {
print("Error:", error)
return nil
}
}{}→Model.self[]→[Model].self
Example:
{
"results": [
{
"name": "Rick",
"image": "https://example.com/image.png"
}
]
}- Outer object → main struct
- Array → use
[] - Inner object → separate struct
struct APIResponse: Codable {
let results: [Character]
}
struct Character: Codable {
let name: String
let image: String
}let result = try JSONDecoder().decode(APIResponse.self, from: data)result.results.first?.name
result.results.first?.imageExplanation:
result→ full responseresults→ arrayfirst→ first item?.name→ safe access
Keep API logic separate from UI.
@State var textData: String = ""
@State var imageURL: String = ""Text(textData)if let url = URL(string: imageURL) {
AsyncImage(url: url)
}AsyncImage(url: URL(string: "https://example.com/image"))- Understand API
- Create struct
- Fetch data
- Store values
- Show in UI
- Struct not matching JSON
- Ignoring nested structure
- Mixing API logic inside UI
- Not converting String to URL
- Not using AsyncImage