Search code examples
watchkitwatchos-2healthkit

Get date/time for HKQuantitySample -> heartRateSample (Watch OS2) from HealthKit


I am using

-(void)updateHeartRate:(NSArray<__kindof HKSample *> *)samples

to retrieve the HearteRate from the internal watch sensor. Depending on the time the app is in background (deactivated) several heartRateSamples must be retrieved using:

if (samples.count>0) {

    for (HKQuantitySample *heartRateSample in samples) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (heartRateSample) {
            NSLog(@"HEART RATE: %@", [@([heartRateSample.quantity doubleValueForUnit:heartRateUnit]) stringValue]);
            }
        });
    }
}

but how can I retrieve the date/time when the specific sample was written to the HealthKit?


Solution

  • The quantity sample's startDate and endDate properties describe when the sample was taken:

    HK_CLASS_AVAILABLE_IOS(8_0)
    @interface HKSample : HKObject
    
    @property (readonly, strong) HKSampleType *sampleType;
    
    @property (readonly, strong) NSDate *startDate;
    @property (readonly, strong) NSDate *endDate;
    
    @end