查询 Healthstore 的静息心率不返回任何值
Query to Healthstore for Resting Heart Rate not returning any values
我在锻炼期间使用下面的代码可以轻松获取心率,但是在查询我自己的心率时(我知道“健康”应用程序中有值)我没有得到任何结果?我做错了什么吗?
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)
}
原来 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 {
}
}
}
我在锻炼期间使用下面的代码可以轻松获取心率,但是在查询我自己的心率时(我知道“健康”应用程序中有值)我没有得到任何结果?我做错了什么吗?
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)
}
原来 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 {
}
}
}