0

I am trying to load HealthKit data and display a total distance and last workout date in a SwiftUI view (for a Widget). I am getting the data in the print statement but it's not getting updated in the HTWidgetView below:

     class WidgetViewModel: ObservableObject {
        
        @Published var workoutDate: Date = Date()
        @Published var totalDistance: Double = 0.0
        
        func getWorkoutDataForWidget() {
            WorkoutManager.loadWorkouts { (workouts, error) in
                DispatchQueue.main.async {
                    guard let unwrappedWorkouts = workouts else { return }
                    
                    if let first = unwrappedWorkouts.first {
                        self.workoutDate = first.startDate
                    }
                
                    let distancesFromWorkouts = unwrappedWorkouts.compactMap {$0.totalDistance?.doubleValue(for: .foot())}
                    
                    let total = distancesFromWorkouts.sum()
                
                    self.totalDistance = total
                    print("TOtal Distance = \(total)")
                    
                }
                
            }
            
        }
    }
    
    extension Sequence where Element: AdditiveArithmetic {
        func sum() -> Element { reduce(.zero, +) }
    } 


struct HTWidgetView: View {

@ObservedObject var viewModel: WidgetViewModel

    var body: some View {
        VStack {
            Text("Last Workout = \(viewModel.workoutDate)")
        Text("Total Distance")
        Text("\(viewModel.totalDistance)")
        }
        .onAppear {
            viewModel.getWorkoutDataForWidget()
        }
    }
}
GarySabo
  • 5,806
  • 5
  • 49
  • 124
  • If `self.totalDistance = total` executes, then `Text("\(viewModel.totalDistance)")` should update as well. This isn't enough code to try to repro, but at a glance, it should work as you expect it. So perhaps the issue is elsewhere – New Dev Sep 01 '20 at 16:21
  • How are you initializing your `WidgetViewModel` in `HTWidgetView`? I don't see a custom initializer and if it is coming from a parent using `@EnvironmentObject` vs `@ObservedObject` might work best. – lorem ipsum Sep 01 '20 at 16:24

0 Answers0