CofeeBean42
CofeeBean42

Reputation: 77

How can I get the highest sample rate historical heart rate data from health store?

I am trying to get heart rate data from health store but when I make a query there are samples that come through with timestamps that shows that there are minutes that go by between the sample measurements. I remember watching an apple video where they were talking about the Quantity series and how these series have one kind of container for multiple data points of bpm data. I also see in the samples that there is a unit of " ___ counts per second" for each of the results so it would make sense if there were multiple datapoints within each of the results from the query but I don't know how to see what's inside of the results or if there is even anything more to them.

This is the code I am using to retrieve the data:

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

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

    /// Predicate for specifying 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
      }

      print(results ?? "Error printing results.")
    
      completion(results as? [HKQuantitySample])
    }
    
    healthStore.execute(query)
  }

Ultimately I want the most frequent heart rate data that is available. Ideally a bpm measurement every 5 - 10 seconds or less. Is this possible if I have not explicitly saved this heart rate data to the health store for a user before trying to access it or does Apple store all of this information in the health store regardless of the circumstances?

Any help is greatly appreciated!

Upvotes: 0

Views: 145

Answers (0)

Related Questions