-->

Query to Healthstore for Resting Heart Rate not re

2019-08-22 03:15发布

问题:

I have no trouble getting heart rates during a workout with the code below, however when querying my own heart rates (and I know there are values in the Health app) I am getting no results? Am I doing anything wrong?

func getuserRestingHeartRate(completion: @escaping (HKQuantitySample) -> Void) {

    guard let restingHeartRateSampleType = HKSampleType.quantityType(forIdentifier: .restingHeartRate) else {
        print("Resting Heart Rate Sample Type is no longer available in HealthKit")
        return
    }

    //1. Use HKQuery to load the most recent samples.
    let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast, 
                                                          end: Date(), 
                                                          options: .strictEndDate)
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)

    //let limit = 1
    let sampleQuery = HKSampleQuery(sampleType: restingHeartRateSampleType,
                                                predicate: mostRecentPredicate,
                                                limit: HKObjectQueryNoLimit,
                                                sortDescriptors:
    [sortDescriptor]) { (query, samples, error) in
        DispatchQueue.main.async {
            guard let samples = samples,
                let mostRecentSample = samples.first as? HKQuantitySample else {
                    print("getUserRestingHeartRate sample is missing")
                    return
            }
            completion(mostRecentSample)
        }
    }
    HKHealthStore().execute(sampleQuery)
}

回答1:

Turns out restingHeartRate has its own permission that is required (in addition to heartRate):

 private func requestAccessToHealthKit() {
        let healthStore = HKHealthStore()

        let allTypes = Set([HKObjectType.quantityType(forIdentifier: .heartRate)!,
                            HKObjectType.quantityType(forIdentifier: .restingHeartRate)!,


        healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
            if !success {

            }


        }
    }