-
SwiftUI View component is developed for handling in-progress and error states when loading data asynchronously. This serves as an exercise in creating abstractions and using Swift generics in practice.
-
SAAsyncView is a SwiftUI View for handling in-progress and error states when loading data asynchronously using async/await.
-
The resulting component is suitable as a ready-made package for use in projects that merely want to load data from URL endpoints and display it via SwiftUI, as well as a starting point for projects that require a more complex structure.
Loading State | Success State | Failure State |
---|---|---|
The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift
compiler.
Once you have your Swift package set up, adding SAAsyncView as a dependency is as easy as adding it to the dependencies
value of your Package.swift
.
https://github.com/ngodacdu/swiftui-async-view
-
You can use AsyncView or AsyncModelView:
- Use AsyncView if not create model and providing an operation (async task)
- Use AsyncModelView if create model and providing an async operation
-
SAAsyncView manages 4 states:
- Empty: display view in empty state
- Loading: display view in loading state, await async task excute
- Success: display view after async task finished
- Failure: an error was thrown during the execution of the async task
AsyncView(
operation: { try await Endpoint.shared.countries() },
empty: {
EmptyView()
},
loading: {
ProgressView()
},
success: { countries in
List(countries) { country in
Text(country.name)
}
},
failure: { error in
Text(error.localizedDescription)
}
)
AsyncModelView(
model: AsyncModel<[Country]>(asyncOperation: { try await Endpoint.shared.countries() }),
empty: {
EmptyView()
},
loading: {
ProgressView()
},
success: { countries in
List(countries) { country in
Text(country.name)
}
},
failure: { error in
Text(error.localizedDescription)
}
)
Ref: https://www.ralfebert.com/ios-app-development/swiftui/asyncview/