How to create an HKQuantitySample from HKStatistics?

I'm trying to process HKStatistics that are heart rates and create an HKQuantitySample so that I can append to a local array. I can't figure out what dates to use for startDate and endDate, currently I'm just using Date()but I would rather be more precise and use the actual sample's date. statistics.StartDate just gives you the date that the statistic collection started, but not the date of the individual sample/statistic. I see that the statistic also has a mostRecentQuantityDateInterval() property but not sure how to use it here.

 private func processStatistics(withStatistics statistics: HKStatistics?) {
        
        // Make sure we got non `nil` parameters.
        guard let statistics = statistics else {
            fatalError("no statistics in processStatistics")
        }
        
        
        // Dispatch to main, because we are updating the interface.
        DispatchQueue.main.async {
            switch statistics.quantityType {
            case HKQuantityType.quantityType(forIdentifier: .heartRate):
                
                if let unwrappedQuantity = statistics.mostRecentQuantity() {
                    let statisticAsHKQuantitySample = HKQuantitySample(type: statistics.quantityType, quantity: unwrappedQuantity, start: Date(), end: Date())
                    
                    self.heartRateSamples.append(statisticAsHKQuantitySample)
                }


Read more here: https://stackoverflow.com/questions/64959144/how-to-create-an-hkquantitysample-from-hkstatistics

Content Attribution

This content was originally published by GarySabo at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: