我需要我的应用程序同步在HealthKit和我们的数据库之间,而它在后台。我无法理解决定HKObserverQueries如何和何时运行其updateHandlers的逻辑。我需要各种不同样本类型的数据,所以我假设我需要对每一个样本进行一个观察者查询。对吗?
根据Apple函数enableBackgroundDeliveryForType的说法,“只要将指定类型的新示例保存到商店,HealthKit就会唤醒您的应用程序。”但是,如果我启用后台交付并执行对血糖和体重的观察查询,那么每当我将数据输入到Health中时,和似乎都会运行它们的更新处理程序。即使我只为其中一种示例类型启用背景传递,这种情况似乎也会发生。为什么?
func startObserving(completion: ((success: Bool) -> Void)!) {
let sampleTypeBloodGlucose = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!
let sampleTypeWeight = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!
// Enable background delivery for blood glucose
self.healthKitStore.enableBackgroundDeliveryForType(sampleTypeBloodGlucose, frequency: .Immediate) {
(success, error) in
if error != nil {
abort()
}
}
// Enable background delivery for weight
self.healthKitStore.enableBackgroundDeliveryForType(sampleTypeWeight, frequency: .Immediate) {
(success, error) in
if error != nil {
abort()
}
}
// Define update handlers for background deliveries
let updateHandlerBloodGlucose: (HKObserverQuery, HKObserverQueryCompletionHandler, NSError?) -> Void = {
query, completionHandler, error in
if error != nil {
abort()
}
// Handle data and call the completionHandler
completionHandler()
}
let updateHandlerWeight: (HKObserverQuery, HKObserverQueryCompletionHandler, NSError?) -> Void = {
query, completionHandler, error in
if error != nil {
abort()
}
// Handle data and call the completionHandler
completionHandler()
}
let observerQueryBloodGlucose = HKObserverQuery(sampleType: sampleTypeBloodGlucose, predicate: nil, updateHandler: updateHandlerBloodGlucose)
healthKitStore.executeQuery(observerQueryBloodGlucose)
let observerQueryWeight = HKObserverQuery(sampleType: sampleTypeWeight, predicate: nil, updateHandler: updateHandlerWeight)
healthKitStore.executeQuery(observerQueryWeight)
completion(success: true)
}发布于 2016-06-24 17:28:39
如果您正在使用HealthKit的后台传递特性,那么是的,您确实需要为观察到的每种类型的数据打开一个HKObserverQuery,并处理updateHandler的调用,并在完成时调用提供的完成。然而,updateHandler of HKObserverQuery是咨询性的,调用并不一定是一对一地对应于对HealthKit数据库的更改(并不总是有足够的信息来确定应用程序处理过什么和没有处理什么,所以有时处理程序可能会在没有新数据时运行)。
不要担心理解或控制updateHandler运行的时间--只需使用它作为触发器来执行其他查询,这些查询实际上会从HealthKit中释放最新的值。例如,如果您需要精确地知道HealthKit中的哪些示例是新的,那么应用程序应该使用HKAnchoredObjectQuery。
https://stackoverflow.com/questions/37986435
复制相似问题