查询Healthstore的Resting Heart Rate不返回任何值

时间:2018-01-22 22:08:52

标签: ios swift health-kit

使用下面的代码在锻炼期间获得心率是没有问题的,但是在查询我自己的心率时(我知道Health应用程序中有值)我没有得到任何结果?我做错了吗?

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 个答案:

答案 0 :(得分:0)

结果restingHeartRate有自己的权限(除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 {

            }


        }
    }