简体   繁体   中英

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. 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. Do i need to build 2 apps , one for watch and phone or the same app? 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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