首页 > 解决方案 > 如何在不使用锻炼课程的情况下在 watchOS 3+ 中获取心率

问题描述

我想通过 watchkit 扩展程序以编程方式收集用户的心率,但不是在锻炼期间。

据我所知,watchOS 3+ 不会在用户移动时收集心率:但是只要他休息一段时间(10 分钟?),我想通过 HealthKit API 以某种方式获得当前的 bpm 值。

标签: watchkitheartbeat

解决方案


由于您有一个配套的 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)
         }
     }
    }
    

请注意,查询需要定期触发。


推荐阅读