-1

I am building an App in Swift for a IOS App. I just want to display the last saved heartrate of the Healthkit. Can someone help me here?

my Authorization request:

static func authorizeHealthKit() {

let HeartRateData: Set = [
    HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!,
    ]
HealthStore.requestAuthorization(toShare: HeartRateData, read: HeartRateData) {_,_ in }

}

    @IBAction func authorizeTapped(_ sender: AnyObject) {
        HeartrateViewController.authorizeHealthKit()
    }

get heart rate:

func fetchHeartRateWithCompletionHandler (_ completionHandler: @escaping (Double?, NSError?)-> ()) {

    let now = Date()
    let startDate = now
    let endDate = now

let HeartRateSampleType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)

let HeartRate = HKStatisticsQuery(quantityType: HeartRateSampleType!, quantitySamplePredicate: predicate, options: .cumulativeSum)
{ query, result, error in
    if result != nil {
        completionHandler(nil, error as NSError?)
        return
    }

    var HeartRateData = 0.0

    if let quantitiy = result!.sumQuantity() {
        let heartRateUnit = HKUnit(from: "count/min")
        HeartRateData = quantitiy.doubleValue(for: heartRateUnit)
    }

    completionHandler(HeartRateData, error as NSError?)

    }
    HeartRateTextField.text = String (describing: HeartRate)



}

but it doesn't display anything in the heart rate text field.

1 Answers1

0

Are you executing the query?

Also, the query you are creating is not very efficient. Your start date and end date are same, and predicate will not find heartRate sample in between them. If you are looking for most recent heart rate sample, read about anchoredObjectQuery.

Akshay Yadav
  • 1
  • 1
  • 3