AsyncView is a SwiftUI View for handling in-progress and error states when loading data asynchronously.

Overview

AsyncView

AsyncView is a SwiftUI View for handling in-progress and error states when loading data asynchronously using async/await:

Countries example

See my blog post "Structuring asynchronous loading operations in SwiftUI" for a tutorial and in-depth explanation of this package.

Example projects

Countries - Branch swiftui3-factbook-asyncview shows a list of countries.

MuseumGuide loads a random artwork from the Met Museum API:

MuseumGuide example

Howto

Endpoints

I recommend to define a type for every API and implement a method for every endpoint/remote call. For example, to load a JSON list of countries:

struct Country: Identifiable, Codable {
    var id: String
    var name: String
}

struct CountriesEndpoints {
    let urlSession = URLSession.shared
    let jsonDecoder = JSONDecoder()

    func countries() async throws -> [Country] {
        let url = URL(string: "https://www.ralfebert.de/examples/v3/countries.json")!
        let (data, _) = try await urlSession.data(from: url)
        return try self.jsonDecoder.decode([Country].self, from: data)
    }
}

Have a look at MetMuseumEndpoints for a more realistic API.

Calling Endpoints

Using AsyncModel and AsyncModelView:

import SwiftUI
import AsyncView

struct CountriesView: View {
    @StateObject var countriesModel = AsyncModel { try await CountriesEndpoints().countries() }

    var body: some View {
        AsyncModelView(model: countriesModel) { countries in
            List(countries) { country in
                Text(country.name)
            }
        }
    }
}

It is also possible to define the model as a separate class:

class CountriesModel: AsyncModel<[Country]> {
    override func asyncOperation() async throws -> [Country] {
        try await CountriesEndpoints().countries()
    }
}

struct CountriesView: View {
    @StateObject var countriesModel = CountriesModel()

    var body: some View {
        AsyncModelView(model: countriesModel) { countries in
            List(countries) { country in
                Text(country.name)
            }
        }
    }
}

For presenting data loaded from a URL endpoint without any additional logic, you can use AsyncView:

import SwiftUI
import AsyncView

struct CountriesView: View {
    var body: some View {
        AsyncView(
            operation: { try await CountriesEndpoints().countries() },
            content: { countries in
                List(countries) { country in
                    Text(country.name)
                }
            }
        )
    }
}
You might also like...
PJFDataSource is a small library that provides a simple, clean architecture for your app to manage its data sources while providing a consistent user interface for common content states (i.e. loading, loaded, empty, and error).
PJFDataSource is a small library that provides a simple, clean architecture for your app to manage its data sources while providing a consistent user interface for common content states (i.e. loading, loaded, empty, and error).

PJFDataSource PJFDataSource is a small library that provides a simple, clean architecture for your app to manage its data sources while providing a co

Placeholder views based on content, loading, error or empty states
Placeholder views based on content, loading, error or empty states

StatefulViewController A protocol to enable UIViewControllers or UIViews to present placeholder views based on content, loading, error or empty states

Placeholder views based on content, loading, error or empty states
Placeholder views based on content, loading, error or empty states

StatefulViewController A protocol to enable UIViewControllers or UIViews to present placeholder views based on content, loading, error or empty states

Swiftui-pressed-states-example - Examples of Pressed States in SwiftUI

Examples of Pressed States in SwiftUI pressed-states.mp4

Easy customizable avatar image asynchronously with progress bar animated
Easy customizable avatar image asynchronously with progress bar animated

JDSwiftAvatarProgress ##Objective-C JDAvatarProgress is available in Objective-C also, JDAvatarProgress Usage To run the example project, clone the re

straightforward networking and error handling with async-await and URLSession

AsyncAwaitNetworkingPlayground How To Run Just clone the project, open it and run. Some notes about AsyncAwaitNetworkingPlayground It's a straightforw

Decodable Simple and strict, yet powerful object mapping made possible by Swift 2's error handling.

Decodable Simple and strict, yet powerful object mapping made possible by Swift 2's error handling. Greatly inspired by Argo, but without a bizillion

Protocol to handle initial Loadings, Empty Views and Error Handling in a ViewController & views
Protocol to handle initial Loadings, Empty Views and Error Handling in a ViewController & views

StatusProvider Protocol to handle initial Loadings, Empty Views and Error Handling in a ViewController & views CocoaPods Podfile pod 'StatusProvider'

Test Library for Swift's Error Handling

CatchingFire CatchingFire is a Swift test framework, which helps making expectations against the error handling of your code. It provides for this pur

ErrorHierarchy - A sibling framework to ActionHierarchy, but specialized for Error handling

Error Hierarchy This is a sibling framework to ActionHierarchy, but specialized

An Xcode12 project for iOS that asynchronously downloads and displays xkcd comics
An Xcode12 project for iOS that asynchronously downloads and displays xkcd comics

AsyncXKCD An Xcode12 project for iOS that asynchronously downloads and displays xkcd comics images and captions. It fills a UITableView as needed to k

Awaiting - Swift @propertyWrapper that waits asynchronously until the value matches a predicate

Introduction @Awaiting is a Swift @propertyWrapper that waits asynchronously unt

PBCircularProgressView is a circular progress view for iOS similar to the app store download progress view.
PBCircularProgressView is a circular progress view for iOS similar to the app store download progress view.

Overview PBCircularProgressView is a circular progress view for iOS similar to the app store download progress view. It also ha

SwiftUI Animation Library. Useful SwiftUI animations including Loading/progress, Looping, On-off, Enter, Exit, Fade, Spin and Background animations that you can directly implement in your next iOS application or project. The library also contains huge examples of spring animations such as Inertial Bounce, Shake, Twirl, Jelly, Jiggle, Rubber Band, Kitchen Sink and Wobble effects. Browse, find and download the animation that fits your needs.
Advanced List View for SwiftUI with pagination & different states

AdvancedList This package provides a wrapper view around the SwiftUI List view which adds pagination (through my ListPagination package) and an empty,

Custom loading button with progress swiftui

CustomLoadingButton Simple Custom Loading Progress Button for SwiftUI Version 1.0.0 This version requires Xcode 11+ SwiftUI iOS 13+ macOS 10.15+ Insta

A small and flexible (well documented)  UIButton subclass with animated loading progress, and completion animation.
A small and flexible (well documented) UIButton subclass with animated loading progress, and completion animation.

ButtonProgressBar-iOS Example For LIVE PREVIEW on Appetize in your browser itself, click here. To run the example project, clone the repo, and run pod

A sliding Sheet from the bottom of the Screen with 3 States build with SwiftUI.
A sliding Sheet from the bottom of the Screen with 3 States build with SwiftUI.

BottomSheet A sliding Sheet from the bottom of the Screen with 3 States build with SwiftUI. Why There have been many different attempts to recreate th

MultiPeer-Progress-iOS - Swift project to demo the use of the MultiPeer framework to send files between iOS devices and show the progress
Comments
  • iOS 14 support

    iOS 14 support

    Appreciate the contribution. The code looks great.

    Any chance of dropping the min deploy target to iOS 14? It looks like it's only .task and .refreshable that would need workaround. Perhaps you could use .onAppear and maybe drop refreshable all together if it's too much bother? (just for iOS 14)? Screenshot 2022-08-02 at 13 43 13

    opened by nashysolutions 0
Owner
Ralf Ebert
Software developer and interaction designer. Making native apps for iOS with Swift and web apps with Ruby on Rails.
Ralf Ebert
Snake Progress shows circular progress for iOS Apps.

SnakeProgress SnakeProgress shows circular progress for iOS Apps. With SnakeProgress With SnakeProgress, you can easily circular progress. @IBOutlet w

null 8 Sep 22, 2022
A Circular SwiftUI progress View

A Circular progress view. There are some controllers to let you customize the progress-view and see which one works better for you. This whole project

Mahdi Bahrami 8 May 7, 2022
Circular progress view for Titanium

ti.circularprogress Circular progress view for Titanium. Using https://github.com/kaandedeoglu/KDCircularProgress (iOS) and https://github.com/owl-93/

null 12 Oct 2, 2022
A simple circular progress view for iOS

CircularProgress A simple circular progress view for iOS. TODOs Gradient Colors Shadow Paths & Colors Multiplied Progress (i.e. progress > 1.0) Usage

i_82 10 Nov 11, 2022
A number of preset loading indicators created with SwiftUI

ActivityIndicatorView A number of preset loading indicators created with SwiftUI We are a development agency building phenomenal apps. Usage Create an

Exyte 956 Dec 26, 2022
TTProgressHUD is a light weight HUD written in SwiftUI meant to display the progress of an ongoing task on iOS.

TTProgressHUD TTProgressHUD is a light weight HUD written in SwiftUI meant to display the progress of an ongoing task on iOS. TTProgressHUD (left) was

Tobias Totzek 184 Dec 27, 2022
I couldn't find a progress bar package, so I created one

swiftbar I couldn't find a progress bar package, so I created one. Installation This package is available via the Swift Package Manager. Simply add .p

null 0 Dec 6, 2021
Easily show HUDs with SwiftUI! Lightweight SwiftUI wrapper for JGProgressHUD for iOS, tvOS, Catalyst.

JGProgressHUD-SwiftUI This is a lightweight and easy-to-use SwiftUI wrapper for JGProgressHUD, giving you access to the large and proven feature set o

Jonas Gessner 78 Dec 21, 2022
GaugeProgressViewStyle adds the Apple Watch gauge view to iOS.

GaugeProgressViewStyle adds the Apple Watch gauge view to iOS. Installation To install GaugeProgressViewStyle, add GaugeProgressViewStyle as a depende

null 29 Jul 28, 2022
A SwiftUI view for dynamically rendering content based upon "loading", "error", and "completed" data loading states.

SwiftUIAsyncContentView A SwiftUI view for dynamically rendering content based upon "loading", "error", and "completed" data loading states.. Installa

CypherPoet 0 Dec 26, 2021