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

前端 未结 3 904
终归单人心
终归单人心 2021-02-13 21:49

How to use : HKUnit

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

3条回答
  •  萌比男神i
    2021-02-13 22:19

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

提交回复
热议问题