Git Product home page Git Product logo

asyncview's Introduction

AsyncView

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

Countries 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
}

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

    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.

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 CountriesView: View {
    var body: some View {
        AsyncView(
            operation: { try await CountriesEndpoints.shared.countries() },
            content: { countries in
                List(countries) { country in
                    Text(country.name)
                }
            }
        )
    }
}

It is also possible to extract the loading operation as a model instance using AsyncModel and use AsyncModelView:

import SwiftUI
import AsyncView

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

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

For more complex models, you can also define the model as a separate class:

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

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

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

Example projects

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

MuseumGuide loads a random artwork from the Met Museum API:

MuseumGuide example

Documentation

See my blog post "Structuring asynchronous loading operations in SwiftUI" for a walk-through tutorial on how to build this package which serves as an in-depth explanation of this package.

asyncview's People

Contributors

ralfebert avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.