我有一个应用程序需要从苹果手表上跟踪用户的心率读数,所以我做了所有我在苹果指南上找到的必要步骤,下面是我正在使用的代码:
static var query: HKObserverQuery?
func startObservingHeartRate() {
guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else {
fatalError("Unable to create a step count sample type")
}
AppDelegate.query = HKObserverQuery(sampleType: heartRateSampleType, predicate: nil, updateHandler: { (query, completionHandler, error) in
if error != nil {
// Perform Proper Error Handling Here...
print("An error occured while setting up the Heart Rate observer.")
}
//Read the last strored heatt rate in add it to the DB
//Add last fetched Heart Rate reading to DB and send it to clips
HealthKitManager().fetchLastStoredHeartRate(completion: { (lastReading, error) in
guard let lastReading = lastReading else {
//There is no heart readings in HealthKit
return
}
//Check if Last HR value is Abnormal
if lastReading.doubleValue > 60 {
//TODO: - Schedule notification
if UIApplication.shared.applicationState == .background {
} else {
//TODO: - Show popup to the user
}
}
})
completionHandler()
})
healthKitStore.execute(AppDelegate.query!)
configureHeartRateObserver()
}
func configureHeartRateObserver() {
guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else {
fatalError("Unable to create a step count sample type")
}
healthKitStore.enableBackgroundDelivery(for: heartRateSampleType, frequency: HKUpdateFrequency.immediate) { (success, error) in
if success {
print("Enabled background delivery of Heart Rate changes")
} else {
print("Failed to enable background delivery of weight changes. ")
}
}
}我在AppDelegate的didFinishLaunchingWithOptions中调用"startObservingHeartRate“,假设一旦健康工具包存储中添加或删除了新的读数,就应该执行这个查询,一切都很好,如果应用程序在后台或被杀死,处理程序将唤醒我的应用程序并进行更新。
但每当我将应用程序放在后台,然后再次将其放在前台时,它就会多次执行观察者查询,即使没有新的读数添加到HealthKit存储中,在这种情况下,我会无缘无故地多次获得相同的最后心率。
请对如何使用这种类型的查询或我需要对当前实现进行的任何更改提出任何建议。
发布于 2017-06-16 00:07:04
如果您想更精确地跟踪添加和删除的心率样本,则应该使用HKAnchoredObjectQuery。HKObserverQuery不保证仅在添加或移除样本时才调用其更新处理程序。请注意,除了HKAnchoredObjectQuery之外,您还必须继续执行HKObserverQuery,因为您也在使用enableBackgroundDelivery(for:frequency:completion:)。
https://stackoverflow.com/questions/44555628
复制相似问题