【问题标题】:Call something when step count is updated当步数更新时调用一些东西
【发布时间】:2017-11-07 17:05:33
【问题描述】:

现在,我正在尝试设置我的应用,以便在用户更新步数时调用一个函数。到目前为止,我有以下代码:

let steps: HKObjectType = HKObjectType.quantityType(forIdentifier: .stepCount)!
    if healthStore.authorizationStatus(for: steps) != HKAuthorizationStatus.notDetermined {
        healthStore.enableBackgroundDelivery(for: steps, frequency: .immediate, withCompletion: { (worked, error) in
            //registers for background data
            if error != nil {
                print(error)
            }
        })
        let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
        let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
            query, completionHandler, error in

            if error != nil {
                print(error)
                abort()
            }

            // Take whatever steps are necessary to update your app's data and UI
            // This may involve executing other queries
            self.getSteps(completion: { (stepCount) in
                print("Step count was updated to \(stepCount)")
            })
            completionHandler()
        }

        healthStore.execute(query)
    }

但是,当用户的 stepCount 在后台更新时不会调用此方法,尽管 getSteps 方法在前台时确实有效。我是否正确地解决了这个问题,或者我正在尝试做的事情是不可能的?

【问题讨论】:

标签: ios swift swift4 healthkit hkobserverquery


【解决方案1】:

您的代码看起来正确。您是在模拟器而不是真实设备上运行它吗?我最近遇到了这个问题,后台交付在模拟器中根本不起作用,但它在真实设备中起作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 2016-04-22
    • 2021-12-05
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多