首页 > 解决方案 > SwiftUI 读取 HealthKit 数据

问题描述

我正在尝试从 SwiftUI 中的 HealthKit 读取 HealthKit 数据。如何访问一天内燃烧的卡路里、心率或步行距离等变量?我发布了我在下面编写的代码。例如,我想将变量放在 TextField 中。

var healthStore = HKHealthStore()

func autorizeHealthKit() {

  // Used to define the identifiers that create quantity type objects.
    let allTypes = Set([HKObjectType.workoutType(),
                        HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
                        HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
                        HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!,
                        HKObjectType.quantityType(forIdentifier: .heartRate)!])
 // Requests permission to save and read the specified data types.
    healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { _, _ in }
}

var body: some View {
    HStack(spacing: 30) {
        ZStack {
            Color.gray.edgesIgnoringSafeArea(.all)

            Text("HeartRate")
            .bold()
        }.frame(width: 140, height: 80)

        ZStack {
            Color.gray.edgesIgnoringSafeArea(.all)

            Text("Calories")
            .bold()
        }.frame(width: 140, height: 80)
    }.onAppear(perform: autorizeHealthKit)
}

}

标签: iosswiftswiftuihealthkitwatchos

解决方案


推荐阅读