I am trying to create an app, that is connected to HealthKit and once there is a workout finished, I'd love to upload some of it's aggregated properties to our serves.
let sampleType = HKObjectType.workoutType()
//1. Enable background delivery for workouts
self.healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
if let unwrappedError = error {
print("could not enable background delivery: \(unwrappedError)")
}
if success {
print("background delivery enabled")
}
}
//2. open observer query
let query = HKObserverQuery(sampleType: sampleType, predicate: HealthKitService.compoundPredicate) { (query, completionHandler, error) in
self.updateWorkouts() {
completionHandler()
}
}
healthStore.execute(query)
This piece of code from AppDelegate works perfectly and gets called right after I finish the workout on my AppleWatch, but only in these cases:
- the state of app does not matter. It works on killed, running or backgrounded app
- it works when iPhone is unlocked
- it never gets called on locked iPhone
My question is. Is this an Apple security feature?
Apple HealthKit docs say nothing about it, but I found similar question from 2015 here on stackoverflow that says so, but without any reference.
Have you faced the same situation? It is pretty important for me to upload the data immediately after the workout ends.
I have enabled Background delivery under HealthKit capabilities, but I haven't enabled any other Background modes.