I'm trying to get the number of workouts performed within the week and want to display it in a view. Is there a way to get the count? I tried to access the count value by the .count property on the array that stores the 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. Any help would be appreciated
class HealthStoreViewModel: ObservableObject {
var selectedWorkoutQuery: HKQuery?
@Published var muscleStrength: [HKWorkoutActivityType] = [HKWorkoutActivityType]()
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
DispatchQueue.main.async {
guard let workouts = samples as? HKWorkout else { return }
self.muscleStrength.append(workouts.workoutActivityType)
}
}
guard let selectedWorkoutQuery = self.selectedWorkoutQuery else { return }
self.healthStore?.execute(selectedWorkoutQuery)
}