2

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

Community
  • 1
  • 1
Arsen
  • 10,815
  • 2
  • 34
  • 46

2 Answers2

2

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().
steve1951
  • 193
  • 7
0

Update : Swift 5

You can specify an ObjectType and how frequently you want it to trigger.

HKHealthStore.enableBackgroundDelivery(for: HKObjectType, frequency: HKUpdateFrequency.immediate) 
Mohammad
  • 1
  • 5