无法在SwiftUI中使用HealthKit显示训练计数

ruarlubt  于 2023-02-15  发布在  Swift
关注(0)|答案(1)|浏览(109)

我正在尝试获取一周内进行的锻炼次数,并希望在视图中显示它。是否有方法获取计数?我尝试通过存储锻炼的数组上的.count属性访问计数值。下面是我正在使用的代码。我省略了授权方法,因为我在获取其他健康变量时使用了该方法。我也收到了此错误“无法将类型为“HKWorkout”的值转换为预期的参数类型“HKWorkoutActivityType”。我尝试更改变量类型,但仍然遇到某种错误。如有帮助,将不胜感激

class HealthStoreViewModel: ObservableObject {

var selectedWorkoutQuery: HKQuery?
 @Published var muscleStrength: [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)
            }
        }

        guard let selectedWorkoutQuery = self.selectedWorkoutQuery else { return }
        self.healthStore?.execute(selectedWorkoutQuery)

    }
8wigbo56

8wigbo561#

此处引用link。您在HKWorkout对象中具有此workoutActivityType属性。当您尝试将HKWorkout类对象分配到HKWorkoutActivityType的枚举定义中时,引发的错误有效

self.muscleStrength.append(workouts.workoutActivityType)

相关问题