Vin*_*shi 18
Swift:心率(bpm)保存到healthkit商店
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
Run Code Online (Sandbox Code Playgroud)
在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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7327 次 |
| 最近记录: |