In my application I query data to compose a "Calorie Profile" for computing BMR and active calories during a workout.
Several users have reported, in addition to having been seen in development, that .height and .bodyMass quantity samples are not found when queried on Apple Watch, but exist when queried on the paired/associated iPhone.
How long is data made available on the Apple Watch?
More specifically, I have a height sample saved on Oct 31st 2019 that is visible in the Health App, and queryable on my app on iPhone. This same sample quantity is not returned on the watch. I'm executing a simple unbounded sample query.
For sanity checking, I just saved a new height sample (today) and refreshed the watch app. Less than 5 seconds later, the data was available. Next test was to delete the new sample, so the previous sample was then Oct 31st again. The query returned nothing again.
extension HKHealthStore {
public func mostRecentHeight(completion: @escaping ((Result<measurement, Error>) -> ())) {
self.execute(HKSampleQuery.lastSample(for: .height, completion: { (height, error) in
guard let heightQuantity = height else {
completion(.failure(QueryError.nilError))
return
}
let height: Measurement = Measurement(value: heightQuantity.quantity.doubleValue(for: .meter()), unit: .meters)
.converted(to: .feet)
// TODO: Convert to preferred unit type
completion(.success(height))
}))
}
}
private extension HKSampleQuery {
static func lastSample(for type: HKQuantityTypeIdentifier, completion: @escaping (HKQuantitySample?, Error?) -> ()) -> HKSampleQuery {
guard let sampleType = HKObjectType.quantityType(forIdentifier: type) else { fatalError("Unknown sample type \(type)") }
let sortDescriptor: NSSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
return HKSampleQuery(sampleType: sampleType, predicate: nil, limit: 1, sortDescriptors: [sortDescriptor], resultsHandler: { (query, samples, error) in
completion(samples?.first as? HKQuantitySample, error)
})
}
}