【发布时间】:2017-06-14 22:21:43
【问题描述】:
我有一个需要从 Apple Watch 跟踪用户心率读数的应用程序,因此我执行了我在 Apple 指南上找到的所有必需步骤,这是我正在使用的代码:
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 存储中没有添加新读数,它也会多次执行观察者查询,在这种情况下,我得到相同的最后心率多次无缘无故。
请就如何使用此类查询或我需要对当前实现进行的任何更改提出任何建议。
【问题讨论】:
标签: ios iphone swift apple-watch healthkit