0

I am trying to read HealthKit Data from HealthKit in SwiftUI. How can I access variables like burned calories, heart rate or walked distance in one day? I posted my code that I wrote below. I want to put the variables for example in a 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)
}

}

user6825883
  • 59
  • 10
  • Reading HealthKit data shouldn't be anything to do with SwiftUI; one is data the other is your view. Create an object that access the HealthKit data and publishes it. Then create views that display the published data. – Paulw11 May 14 '20 at 10:14
  • I know but how can I do that? – user6825883 May 14 '20 at 10:18
  • First you need to understand how SwiftUI works with data. It is a declarative UI that consumes a data model. If you don't understand that, look into some SwiftUI tutorials until you follow how things like `@ObservableObject` and `@Published` work. Then read up on how to query for HealthKit data. Then you will understand query for health kit data, add it to an observable model and create SwiftUI code to display that model data. You won't have any HealthKit code in your view. – Paulw11 May 14 '20 at 10:21
  • Do you have a Code example for that? – user6825883 May 14 '20 at 10:28
  • No, I'm afraid your question needs more focus on to a specific problem. There are lots of tutorials on SwiftUI, including some from Apple as well as Hacking With Swift's Paul Hudson. I think once you understand how SwiftUI works you will see how to approach your problem. – Paulw11 May 14 '20 at 10:31

0 Answers0