watchkit - 如何在不使用锻炼课程的情况下在 watchOS 3+ 中获取心率
问题描述
我想通过 watchkit 扩展程序以编程方式收集用户的心率,但不是在锻炼期间。
据我所知,watchOS 3+ 不会在用户移动时收集心率:但是只要他休息一段时间(10 分钟?),我想通过 HealthKit API 以某种方式获得当前的 bpm 值。
解决方案
由于您有一个配套的 iPhone 应用程序,您可以从那里查询心率更新。
- 你只需要有一个配对 Apple Watch 的 iPhone(这很明显)
- 默认 Apple Watch 心率监测器应用程序仅在处于前台时才立即更新 HealthKit 数据。
当默认 Apple Watch 心率监测器应用程序处于后台时,它会每隔 9-10 分钟更新一次 HealthKit 数据。这段代码应该可以完成工作:
import UIKit import HealthKit class ViewController: UIViewController { @IBOutlet weak var heartRateLabel: UILabel! @IBOutlet weak var timeStampLabel: UILabel! var hkStore: HKHealthStore? let heartRateUnit: HKUnit = HKUnit.count().unitDivided(by: .minute()) var healthStore: HKHealthStore? override func viewDidLoad() { super.viewDidLoad() healthStore = HKHealthStore() let sampleTypes = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)! healthStore?.requestAuthorization(toShare: [sampleTypes], read: [sampleTypes], completion: { (success, error) in if (error != nil) { print(error!.localizedDescription) } }) getSamples() } func getSamples() { let heartrate = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) let sort = [ NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) ] let sampleQuery = HKSampleQuery(sampleType: heartrate!, predicate: nil, limit: 1, sortDescriptors: sort, resultsHandler: { [unowned self] (query, results, error) in if let results = results as? [HKQuantitySample] { let sample = results[0] as HKQuantitySample let value = sample.quantity.doubleValue(for: self.heartRateUnit) let rate = results[0] print(value, rate) self.updateHeartRate(samples: results) } }) healthStore?.execute(sampleQuery) } func updateHeartRate(samples: [HKSample]?) { guard let heartRateSamples = samples as? [HKQuantitySample] else {return} DispatchQueue.main.async { guard let sample = heartRateSamples.first else{return} let value = sample.quantity.doubleValue(for: self.heartRateUnit) self.heartRateLabel.text = String(UInt16(value)) let date = sample.startDate let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" self.timeStampLabel.text = dateFormatter.string(from: date) } } }
请注意,查询需要定期触发。
推荐阅读
- php - 更新到 php 7 后密码框不显示
- html - Bootstrap - 菜单下拉菜单下推内容
- c# - 建立连接后如何在c#中备份数据库
- drupal - Drupal 7:来自钩子菜单的打印主题,性能良好
- javascript - 如何使用 Javascript 检测用户在我的网站中的首次访问?
- javascript - 在反应生产构建中删除控制台日志语句?
- angular - 等待两种以角度返回可观察对象的方法
- react-native - 无法读取属性导航未定义
- java - 如何从 android studio 中的片段打开对话框?
- java - 始终等待页面加载到 PageObjects