简体   繁体   English

从 healthKit 中提取心率

[英]Extract heart rate from healthKit

I'm trying to build an app with swift which will extract the heart rate from iwatch and display it to the user along with it will play some music in the user's iphone.我正在尝试使用 swift 构建一个应用程序,它将从 iwatch 中提取心率并将其显示给用户,同时它会在用户的 iphone 中播放一些音乐。 Pretty new to ios ,so im trying to figure out how to extract data from healthkit in iwatch and sync it with the mobile app. ios 非常新,所以我试图弄清楚如何从 iwatch 中的 healthkit 中提取数据并将其与移动应用程序同步。 Do i need to build 2 apps , one for watch and phone or the same app?我需要构建 2 个应用程序,一个用于手表和手机还是同一个应用程序? and how to integrate health kit since i have just enabled it in the target->capabilities.以及如何集成健康包,因为我刚刚在目标-> 功能中启用了它。

public func subscribeToHeartBeatChanges() {

  // Creating the sample for the heart rate
  guard let sampleType: HKSampleType =
    HKObjectType.quantityType(forIdentifier: .heartRate) else {
      return
  }

  /// Creating an observer, so updates are received whenever HealthKit’s
  // heart rate data changes.
  self.heartRateQuery = HKObserverQuery.init(
    sampleType: sampleType,
    predicate: nil) { [weak self] _, _, error in
      guard error == nil else {
        log.warn(error!)
        return
      }

      /// When the completion is called, an other query is executed
      /// to fetch the latest heart rate
      self.fetchLatestHeartRateSample(completion: { sample in
        guard let sample = sample else {
          return
        }

        /// The completion in called on a background thread, but we
        /// need to update the UI on the main.
        DispatchQueue.main.async {

          /// Converting the heart rate to bpm
          let heartRateUnit = HKUnit(from: "count/min")
          let heartRate = sample
            .quantity
            .doubleValue(for: heartRateUnit)

          /// Updating the UI with the retrieved value
          self?.heartRateLabel.setText("\(Int(heartRate))")
        }
      })
  }
}

public func fetchLatestHeartRateSample(
  completion: @escaping (_ sample: HKQuantitySample?) -> Void) {

  /// Create sample type for the heart rate
  guard let sampleType = HKObjectType
    .quantityType(forIdentifier: .heartRate) else {
      completion(nil)
    return
  }

  /// Predicate for specifiying start and end dates for the query
  let predicate = HKQuery
    .predicateForSamples(
      withStart: Date.distantPast,
      end: Date(),
      options: .strictEndDate)

  /// Set sorting by date.
  let sortDescriptor = NSSortDescriptor(
    key: HKSampleSortIdentifierStartDate,
    ascending: false)

  /// Create the query
  let query = HKSampleQuery(
    sampleType: sampleType,
    predicate: predicate,
    limit: Int(HKObjectQueryNoLimit),
    sortDescriptors: [sortDescriptor]) { (_, results, error) in

      guard error == nil else {
        print("Error: \(error!.localizedDescription)")
        return
      }

      completion(results?[0] as? HKQuantitySample)
  }

  self.healthStore.execute(query)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM