I’m trying to get the number of workouts performed within the week and display the count in a view and also display the workout like you see in the Apple Fitness app. I’m having issues reading the data and displaying it. I’m trying to only get functional strength training and traditional strength training workouts. Below is the code I’m using. I’m omitting the authorization method because I have that with other health variables I’m getting. Also, when I try to get the workoutActivity type to display, nothing is showing up. I’ve looked over apple’s healthkit documentation but getting a big confused/lost as a beginner, particularly with the workout data. Any help would be appreciated.
class HealthStoreViewModel: ObservableObject {
var selectedWorkoutQuery: HKQuery?
@Published var muscleStrength: [HKWorkout] = [HKWorkout]()
func getStrengthTrainingWorkouts() {
let date = Date()
let startDate = Calendar.current.dateInterval(of: .weekOfYear, for: date)?.start
let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: nil, options: .strictStartDate)
let traditionalStrengthTrainingPredicate = HKQuery.predicateForWorkouts(with: .traditionalStrengthTraining)
let functionalStrengthTrainingPredicate = HKQuery.predicateForWorkouts(with: .functionalStrengthTraining)
let strengthCompound = NSCompoundPredicate(andPredicateWithSubpredicates: [datePredicate, traditionalStrengthTrainingPredicate, functionalStrengthTrainingPredicate])
let selectedWorkoutQuery = HKSampleQuery(sampleType: HKWorkoutType.workoutType(), predicate: strengthCompound, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { strengthQuery, samples, error in
guard let samples = samples else {
fatalError("An error has occured \(error?.localizedDescription)")
}
DispatchQueue.main.async {
if let workouts = samples as? [HKWorkout] {
for workout in workouts {
self.muscleStrength.append(workout)
}
}
}
}
self.healthStore?.execute(selectedWorkoutQuery)
}
Here is the view I would like to display the count and workouts but nothing is showing
struct MuscleView: View {
@ObservedObject var healthStoreVM: HealthStoreViewModel
var body: some View {
List(healthStoreVM.muscleStrength, id: \.self) {
workout in
Text("\(workout.workoutActivityType.rawValue)")
}
}
}