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

9
  • Is your @State var on a ViewModel? Is your ViewModel an @ObservableObject if so you should change that to an @Published Commented Jun 3, 2021 at 13:51
  • When do you call the function? When the view appears? Commented Jun 3, 2021 at 14:00
  • @xTwisteDx It's directly in my View, I'll look into Viewmodels in SwiftUI, thanks Commented Jun 3, 2021 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. Commented Jun 3, 2021 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. stackoverflow.com/questions/67538721/… Commented Jun 3, 2021 at 14:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.