Heart Rate data on apple Watch

前端 未结 4 571
长发绾君心
长发绾君心 2020-11-28 04:23

Can we access the heart rate directly from the apple watch? I know this is a duplicate question, but no one has asked this in like 5 months. I know you can access it from th

4条回答
  •  醉梦人生
    2020-11-28 04:50

    After exploring HealthKit and WatchKit Extension, My findings are as follows:

    1. We do not need the WatchKit Extension to get the Heart Rate Data.

    2. You just need to have an iPhone with paired Apple watch (which is obvious)

    3. The Default Apple Watch Heart Rate monitor app updates the HealthKit data immediately only when it is in the foreground.

    4. When the Default Apple Watch Heart Rate monitor app is in the Background, it updates the HealthKit data at the interval of 9-10 mins.

    5. To get the Heart rate data from the HealthKit following query needs to be fired periodically.

      func getSamples() {
      
          let heathStore = HKHealthStore()
      
          let heartrate = HKQuantityType.quantityType(forIdentifier: .heartRate)
          let sort: [NSSortDescriptor] = [
              .init(key: HKSampleSortIdentifierStartDate, ascending: false)
          ]
      
          let sampleQuery = HKSampleQuery(sampleType: heartrate!, predicate: nil, limit: 1, sortDescriptors: sort, resultsHandler: resultsHandler)
      
          heathStore.execute(sampleQuery)
      
      }
      
      func resultsHandler(query: HKSampleQuery, results: [HKSample]?, error: Error?) {
      
          guard error == nil else {
              print("cant read heartRate data", error!)
              return
          }
      
          guard let sample = results?.first as? HKQuantitySample else { return }
      
          // let heartRateUnit: HKUnit = .init(from: "count/min")
          // let doubleValue = sample.quantity.doubleValue(for: heartRateUnit)
      
          print("heart rate is", sample)
      }
      

    Please update me if anyone gets more information.
    Happy Coding.

    Update

    I've updated your code to be clear and general, and be aware that you need to get authorization for reading HeathKit data and adding info.plist key Privacy - Health Records Usage Description

提交回复
热议问题