1

I am trying to fetch Heart Rate Data from HealthKit iOS by putting filter using HKQuery.predicateForObjects By using the following code:

let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyHeartRateMotionContext, allowedValues: ["active"])


        var interval = DateComponents()
        interval.day = 1
        let query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: predicate, options: [.discreteAverage], anchorDate: startDate, intervalComponents:interval)
        query.initialResultsHandler = { query, results, error in
            if error != nil {

                return
            }

I tried different combinations for putting values in a different way

let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyHeartRateMotionContext, allowedValues: ["1"])

OR

let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyHeartRateMotionContext, allowedValues: ["active"])

OR

let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyHeartRateMotionContext, allowedValues: [HKHeartRateMotionContext.sedantary])

I am not getting if am doing anything wrong somewhere in my code.

Please correct me.

Thanks in advance enter image description here

Piyush Bansal
  • 1,635
  • 4
  • 16
  • 39
  • What about `HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyHeartRateMotionContext, allowedValues: [HKHeartRateMotionContext.active])`? – staticVoidMan May 21 '19 at 09:52
  • Following error I am getting when I tried with [HKHeartRateMotionContext.active] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Expected all metadata values to be of type NSNumber, NSDate, or NSString. Received __C.HKHeartRateMotionContext' – Piyush Bansal May 21 '19 at 10:20
  • 1
    Maybe with `HKHeartRateMotionContext.active.rawValue` instead? – Larme May 21 '19 at 10:47
  • @PiyushBansal Ok, then what about `HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyHeartRateMotionContext, allowedValues: ["2"])`? – staticVoidMan May 21 '19 at 10:50
  • https://developer.apple.com/documentation/healthkit/hkheartratemotioncontext/active value is 2. But using rawValue should be better than using number magic. – Larme May 21 '19 at 11:56
  • @Larme Yup, true that – staticVoidMan May 21 '19 at 11:59
  • But error is not nil? Could you check if you don't put the `allowedValue:` param if it returns at least some values? If it does, check the date of each items, or the interval. – Larme May 21 '19 at 21:28

0 Answers0