Query to Healthstore for Resting Heart Rate not returning any values

最后都变了- 提交于 2019-12-11 16:59:02

问题


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 {

            }


        }
    }


来源:https://stackoverflow.com/questions/48391037/query-to-healthstore-for-resting-heart-rate-not-returning-any-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!