0

I'm stuck on something which should be trivial, using SwiftUI. I am pulling some data back from my API, and simply want to show each item on my view with ForEach.

I have the following function:

@State var workoutVideoList: GetWorkoutVideoListResponse!

func GetWorkoutVideoList() {
    loadingWorkoutVideoList = true
    
    PtPodsApiService.GetWorkoutList(firebaseToken: firebaseAuthToken) { (workoutListResult) -> () in
        DispatchQueue.main.async() {
            workoutVideoList = workoutListResult
            loadingWorkoutVideoList = false
        }
    }
}

I then want to show another view and pass this object into it:

if workoutVideoList != nil {
    BookAppointmentView(workoutVideoList: workoutVideoList)
}
else {
    Text("Nope")
}

For whatever reason, my main thread sees workoutVideoList as nil, even though it's been assigned. I thought using the dispatcher to assign it would solve the problem, but no joy!

Any idea what I'm doing wrong here?

Thanks

JMK
  • 27,273
  • 52
  • 163
  • 280
  • Is your @State var on a ViewModel? Is your ViewModel an `@ObservableObject` if so you should change that to an `@Published` – xTwisteDx Jun 03 '21 at 13:51
  • When do you call the function? When the view appears? – Lukas Jun 03 '21 at 14:00
  • @xTwisteDx It's directly in my View, I'll look into Viewmodels in SwiftUI, thanks – JMK Jun 03 '21 at 14:01
  • @Lukas When a button is pressed, the button doesn't show until `loadingWorkoutVideoList` is true – JMK Jun 03 '21 at 14:01
  • 1
    give `@State` a default value `@State var workoutVideoList: GetWorkoutVideoListResponse = false` and use `onAppear` to call `GetWorkoutVideoList()` but ideally you will eventually get this working in a ViewModel. – lorem ipsum Jun 03 '21 at 14:02
  • 1
    I've answered a MVVM question with SwiftUI here, feel free to have a look. It's very simple in Swift. https://stackoverflow.com/questions/67538721/how-to-use-mvvm-correctly-in-swiftui/67539836#67539836 – xTwisteDx Jun 03 '21 at 14:07
  • @xTwisteDx I'm getting flashbacks from when I used to work with WPF, thanks will have a read! – JMK Jun 03 '21 at 14:25
  • @loremipsum I was calling the function from OnInit, moved the call to OnAppear and it's working now!! OnInit must be too early, if you want to answer the question I'll mark it as correct! Thanks! – JMK Jun 03 '21 at 14:40
  • I'm glad it worked I answered below – lorem ipsum Jun 03 '21 at 16:51

1 Answers1

1

Give @State a default value @State var workoutVideoList: GetWorkoutVideoListResponse = false and use onAppear to call GetWorkoutVideoList() but ideally you will eventually get this working in a ViewModel.

lorem ipsum
  • 21,175
  • 5
  • 24
  • 48