2

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?

LFHS
  • 295
  • 1
  • 2
  • 15
  • It might be possible in for delivery in background as long as the device is unlocked... Please check out this answer for more info particularly Victor Sigler's answer https://stackoverflow.com/questions/26375767/healthkit-background-delivery-when-app-is-not-running? – Louis Leung Nov 07 '17 at 21:32

1 Answers1

2

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

lzt
  • 98
  • 6