ios - Apple HealthKit - 后台更新未触发

标签 ios swift background healthkit

我正在尝试执行一些由 Apple Health Kit 更改触发的操作,这些操作在我的 Swift iOS 应用程序的后台触发。

这是我的 AppDelegate:

var healthManager : HealthManager?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


    healthManager = HealthManager.sharedInstance


    return true
}

在 HealthManager 类的初始化中,我授权使用 Health Kit 并调用:

    var sampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
    var predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.StrictStartDate)
    var query = HKObserverQuery(sampleType: sampleType, predicate: predicate, updateHandler: stepsChangedHandler)

    healthKitStore.executeQuery(query)
    healthKitStore.enableBackgroundDeliveryForType(sampleType, frequency: .Immediate, withCompletion: {(succeeded, error) in
        if succeeded {
            println("Enabled background delivery of step changes")
        } else {
            if let theError = error {
                print("Failed to enable background delivery of step changed. ")
                println("Error = \(theError)")
            }
        }
    })

当应用程序打开时,这工作得很好 - 当有健康套件更新时,将调用stepsChangedHandler,但当应用程序失去焦点时,它永远不会被调用。我四处搜寻并找到了一些想法,但似乎没有一个修复方法对我有用。

谢谢!

最佳答案

你所拥有的应该可以工作,但我在 iOS 8.4 和 Xcode 6.4 之前使用模拟器的经验是,不会触发后台更新。然而,在我的测试中,这确实可以在设备上运行。要亲自尝试,请在设备上连接并运行您的应用程序,然后切换到 Health.app 并添加相关数据点。

如果您的查询设置为立即更新,您应该在控制台中看到日志消息。确保 stepsChangedHandler 包含 completionHandler()

根据文档,查询在单独的后台线程上运行,因此您的 appdelegate 代码只会在初始启动时调用。

关于ios - Apple HealthKit - 后台更新未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31141487/

相关文章:

ios - iOS开发读取JSON字符串时如何保持原来的顺序?

iOS:核心数据合并策略如何影响 NSManagedObjectContext 保存和刷新操作

swift - 字典顺序错误 - JSON

android - 如何检测Android应用何时进入后台并回到前台

CSS "see-through"背景 - 疯狂导航菜单问题

iphone - 如何 "Auto SMS Sender"工作 - 在后台发送短信

ios - UIFont 自定义样式设置

iphone - 自定义 UIITableViewCell 中的 UIImageView 在重新加载时不会切换

properties - Swift 类 : Property not initialized at super. init 调用中出现错误

operators - swift 1.2 ??运算符(operator)