Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS HealthKit how to save Heart Rate (bpm) values? Swift

How to use : HKUnit

Sample type Unit type Unit name Unit string Heart Rate count/time Beats per Minute "count/min”

like image 491
Vinod Joshi Avatar asked Dec 03 '14 10:12

Vinod Joshi


1 Answers

In Swift 3:

func saveHeartRate(date: Date = Date(), heartRate heartRateValue: Double, completion completionBlock: @escaping (Bool, Error?) -> Void) {
    let unit = HKUnit.count().unitDivided(by: HKUnit.minute())
    let quantity = HKQuantity(unit: unit, doubleValue: heartRateValue)
    let type = HKQuantityType.quantityType(forIdentifier: .heartRate)!

    let heartRateSample = HKQuantitySample(type: type, quantity: quantity, start: date, end: date)

    self.healthKitStore.save(heartRateSample) { (success, error) -> Void in
        if !success {
            print("An error occured saving the HR sample \(heartRateSample). In your app, try to handle this gracefully. The error was: \(error).")
        }
        completionBlock(success, error)
    }
}
like image 50
He Yifei 何一非 Avatar answered Nov 15 '22 22:11

He Yifei 何一非