Skip to content

AsyncView is a SwiftUI View that handles in-progress and error states when loading data asynchronously using async/await. It's like AsyncImage but for data.

License

Notifications You must be signed in to change notification settings

ralfebert/AsyncView

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AsyncView

AsyncView is like AsyncImage, but for data. It is a SwiftUI View that handles in-progress and error states when loading data using async/await.

Loading states example

Howto

Endpoints

I recommend to define a type for every API and implement a method for every endpoint/remote call. For example:

struct Artwork: Codable {
    var objectID: String
    var objectName: String
}

class MetMuseumEndpoints {
    let urlSession = URLSession.shared
    let jsonDecoder = JSONDecoder()
    
    static let shared = MetMuseumEndpoints()

    func artwork(id: Int) async throws -> [Artwork] {
        let url = URL(string: "https://collectionapi.metmuseum.org/public/collection/v1/objects/\(id)")!
        let (data, _) = try await urlSession.data(from: url)
        return try self.jsonDecoder.decode([Artwork].self, from: data)
    }
}

Have a look at MetMuseumEndpoints for a more comprehensive example.

Loading data for SwiftUI views asynchronously

For presenting data loaded from a URL endpoint directly in a SwiftUI View, you can use AsyncView:

import SwiftUI
import AsyncView

struct ArtworkView: View {
    var body: some View {
        AsyncView(
            operation: { try await MetMuseumEndpoints.shared.artwork(id: 45734) },
            content: { artwork in
                Text(artwork.objectName)
            }
        )
    }
}

Example projects

MuseumGuide shows a gallery of artwork using the Met Museum API:

MuseumGuide example

About

AsyncView is a SwiftUI View that handles in-progress and error states when loading data asynchronously using async/await. It's like AsyncImage but for data.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages