AsyncImage, Loading States and Error Screens
AsyncImage
swift
AsyncImage(url: URL(string: "https://picsum.photos/300")) { image in
image
.resizable()
.scaledToFill()
} placeholder: {
ProgressView()
}
.frame(width: 150, height: 150)
.clipShape(RoundedRectangle(cornerRadius: 16))
Handle Failure with Phases
swift
AsyncImage(url: url) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image.resizable().scaledToFill()
case .failure:
Image(systemName: "photo.badge.exclamationmark")
.foregroundStyle(.secondary)
@unknown default:
EmptyView()
}
}
.frame(width: 100, height: 100)
.clipped()
Caching:
AsyncImage uses the URL cache but does not guarantee strong caching. For image-heavy apps consider a small caching library, or your own cache, after you measure a real need.
A Load State Enum
Model every possible screen condition. It prevents impossible combinations such as showing a spinner and an error at the same time.
swift
enum LoadState<Value> {
case idle
case loading
case loaded(Value)
case failed(String)
}
@MainActor
@Observable
final class UsersModel {
var state: LoadState<[User]> = .idle
func load() async {
state = .loading
do {
let users: [User] = try await APIClient().get("https://jsonplaceholder.typicode.com/users")
state = .loaded(users)
} catch {
state = .failed(error.localizedDescription)
}
}
}
struct UsersView: View {
@State private var model = UsersModel()
var body: some View {
NavigationStack {
Group {
switch model.state {
case .idle, .loading:
ProgressView("Loading...")
case .loaded(let users) where users.isEmpty:
ContentUnavailableView("No users", systemImage: "person.slash")
case .loaded(let users):
List(users) { Text($0.name) }
case .failed(let message):
ContentUnavailableView {
Label("Could not load", systemImage: "wifi.slash")
} description: {
Text(message)
} actions: {
Button("Try again") { Task { await model.load() } }
.buttonStyle(.borderedProminent)
}
}
}
.navigationTitle("Users")
.task { await model.load() }
}
}
}
Skeleton Placeholder
swift
List(0..<6, id: \.self) { _ in
Text("Placeholder title goes here")
}
.redacted(reason: .placeholder)
Tip: Always design 4 screens for network data: loading, content, empty and error. Beginners often build only the content screen.
Conclusion
Good network screens handle every state. A small enum with loading, loaded and failed cases keeps the code clean and the UI honest.
Quick Summary: Use AsyncImage with phases, model screen states with an enum, and show ProgressView, empty and retry views.

