Search code examples
swifthealthkit

HKAnchoredObjectQuery updateHandler calls only once


I have ViewController in an iPhone app:

class ViewController: UIViewController {
    private let healthStore = HKHealthStore()
    private let heartRateUnit = HKUnit(fromString: "count/min")
    private var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))

    override func viewDidLoad() {
        super.viewDidLoad()

        if let query = createHeartRateStreamingQuery(NSDate()) {
            healthStore.executeQuery(query)
        }
    }

     func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {
        guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return .None }

        let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error)  in }

        heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) in
            self.updateHeartRate(samples)
        }

        return heartRateQuery
    }

But heartRateQuery.updateHandler calls only once while I'm using Workout app.

It looks like the same error - https://forums.developer.apple.com/thread/14571 and Monitor heart rate from HealthKit --> HKAnchoredObjectQuery only called after applicationDidBecomeActive (BUG or FEATURE?)


Solution

  • You need to enable background delivery for your sample type (heart rate). Lookup the method

    HKHealthStore.enableBackgroundDeliveryForType()
    

    I execute this method prior to

    HKHealthStore.executeQuery().