如何在不使用健身课程的情况下在watchOS 3+中获得炉膛速率

时间:2019-05-19 21:23:08

标签: watchkit heartbeat

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

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

1 个答案:

答案 0 :(得分:0)

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

请注意,该查询需要定期启动。