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

前端 未结 3 862
终归单人心
终归单人心 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条回答
  •  日久生厌
    2021-02-13 22:14

    Swift : Heart Rate (bpm) save into healthkit store

     private func saveHeartRateIntoHealthStore(height:Double) -> Void
        {
            // Save the user's heart rate into HealthKit.
            let heartRateUnit: HKUnit = HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit())
            let heartRateQuantity: HKQuantity = HKQuantity(unit: heartRateUnit, doubleValue: height)
    
            var heartRate : HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
            let nowDate: NSDate = NSDate()
    
            let heartRateSample: HKQuantitySample = HKQuantitySample(type: heartRate
                , quantity: heartRateQuantity, startDate: nowDate, endDate: nowDate)
    
            let completion: ((Bool, NSError!) -> Void) = {
                (success, error) -> Void in
    
                if !success {
                    println("An error occured saving the Heart Rate sample \(heartRateSample). In your app, try to handle this gracefully. The error was: \(error).")
    
                    abort()
                }
    
            }
    
            self.healthStore!.saveObject(heartRateSample, withCompletion: completion)
    
        }// end saveHeartRateIntoHealthStore
    

提交回复
热议问题