使用HKObserverQuery观察HealthKit数据的变化 [英] Observing changes in HealthKit data using HKObserverQuery

查看:436
本文介绍了使用HKObserverQuery观察HealthKit数据的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我设置HKObserverQuery时,更新处理程序总是立即被调用(我没想到的)。当我通过Health.app添加数据点时,它也会被调用,正如您所期望的那样。我倾向于认为我没有使用完成处理程序做正确的事情,但文档在这里应该发生的事情上相当稀疏。

When I setup an HKObserverQuery, the update handler always gets immediately called (something I didn't expect). It also gets called when I add data points through Health.app, as you would expect. I am tending to think I am not doing something right with the completion handler, but the docs are fairly sparse on what is supposed to happen here.

问题:基本上我正在做的事情。这是预期的行为,还是我错过了什么?

func listenForUpdates() {
    let bodyMassType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
    let updateHandler: (HKObserverQuery!, HKObserverQueryCompletionHandler!, NSError!) -> Void = { query, completion, error in
        if !error {
            println("got an update")
            // ... perform a sample query to get the actual data
            completion() // is this the right thing to do?
        } else {
            println("observer query returned error: \(error)")
        }            
    }
    let query = HKObserverQuery(sampleType: bodyMassType, predicate: nil, updateHandler: updateHandler)
    healthStore?.executeQuery(query)
}

编辑:只有在没有错误时才会调用已发现的完成处理程序,因此移入!错误块。未授权应用时出现错误。

Edit: discovered completion handler should only be called when there wasn't an error, so moved into the !error block. An error is present when the app is not authorized.

推荐答案

是的,这是预期的行为。第一次执行时将始终调用更新处理程序,以便您可以使用它来获取初始数据(从示例查询,锚定对象查询等)并填充UI。

Yes, this is expected behavior. The update handler will always be called on first execution so that you can use it to fetch your initial data (from your sample query, anchored object query, etc) and populate your UI.

只有在您打算使用后台交付时才需要完成处理程序,它会通知HealthKit您已收到并处理了所需的数据,以便HealthKit知道停止在后台启动您的应用程序。如果您尚未注册应用程序以进行后台交付,那么完成处理程序本质上是一个无操作程序,您无需担心它。

The completion handler is only necessary if you intend to use background delivery, it informs HealthKit that you have received and processed the data you need so that HealthKit knows to stop launching your app in the background. If you have not registered your app for background delivery, then the completion handler is essentially a no-op and you don't need to worry about it.

这篇关于使用HKObserverQuery观察HealthKit数据的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆