Search code examples
iosswiftswift4healthkithkobserverquery

Call something when step count is updated


Right now, I'm trying to set up my app so that a function is called when the user updates their step count. So far, I have the following code:

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

However, this isn't called when the user's stepCount is updated in the background, although the getSteps method does work when in the foreground. Am I going about this correctly, or is what I'm trying to do just not possible?


Solution

  • Your code looks correct. Are you running it on a simulator instead of a real device? I have had this problem recently and background delivery does not work at all in simulator but it works in a real device