Ios 更新步骤计数时调用某个对象

Ios 更新步骤计数时调用某个对象,ios,swift,swift4,healthkit,hkobserverquery,Ios,Swift,Swift4,Healthkit,Hkobserverquery,现在,我正在尝试设置我的应用程序,以便在用户更新步数时调用函数。到目前为止,我有以下代码: let steps: HKObjectType = HKObjectType.quantityType(forIdentifier: .stepCount)! if healthStore.authorizationStatus(for: steps) != HKAuthorizationStatus.notDetermined { healthStore.enableBackgr

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

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)
    }

但是,在后台更新用户的步数时不会调用此函数,尽管
getSteps
方法在前台时确实有效。我这样做是否正确,或者我正在尝试做的是不可能的?

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

只要设备解锁,就有可能在后台交付。。。请查看此答案以了解更多信息,尤其是维克多·西格勒的答案?