skip to Main Content

I wanted to get the API from the site and show it to the ContentView.
However, the function that receives the API that I wrote in the onAppear function attached to the List does not work.
So when access the array where you store the data, this app stops because it said you accessed nil.

var body: some View {
    Color.pink.opacity(0.2)
    List(weatherFetcher.weathers.first!.response.body.items.item, id: .id) { weather in
        VStack(alignment: .leading) {
            Text(weather.category)
                .font(.headline)
            Text(weather.fcstValue)
                .font(.subheadline)
        }
    }
    .onAppear {
        weatherFetcher.fetchWeathers() // Try BreakPoint
        print("Pass")
    }
}

I tried make breakpoint. However, the compiler passed the pew during debugging.
I also checked using print, but "Pass" did not appear in the console window.
Isn’t the onAppear function running before the List appears?

2

Answers


  1. The key point lorem ipsum is making is that this line is evaluated before onAppear:

    List(weatherFetcher.weathers.first!.response.body.items.item, id: .id) { weather in
    

    Then, if onAppear causes a @State value to be changed (or a @Published property that is being observed), then the body will be reevaluated.

    You must handle the case where weathers is empty.

    Login or Signup to reply.
  2. Presumably weatherFetcher.fetchWeathers() is an asynchronous call to retrieve some model data. The desired behavior is that when the user navigates to this view, the weather data is loaded and displayed. This means that you will need to add some empty state to display while the weather data is being fetched, such as a loader with a message.

    Your body logic should account for this by having a branch for when weatherFetcher.weathers is empty/nil. In that case, an empty state view will displayed instead of the List. Once the view appears (initially displaying the empty state), the weather data will load and populate weatherFetcher.weathers, which property should be published by the weatherFetcher class. The view will then respond to the published change and redraw, with the body logic displaying the list now that weathers is no longer nil.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search