问题
How can I get the most recent weight entry from healthkit data?
My code is only returning the first weight entry ever recorded.
Is is possible to get only the last entry recorded without specifying a date range?
Here is my code that gets the first entry:
class HealthStore {
private let healthStore = HKHealthStore()
private let bodyMassType = HKSampleType.quantityType(forIdentifier: .bodyMass)!
func authorizeHealthKit(completion: @escaping ((_ success: Bool, _ error: Error?) -> Void)) {
if !HKHealthStore.isHealthDataAvailable() {
return
}
let readDataTypes: Set<HKSampleType> = [bodyMassType]
healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) in
completion(success, error)
}
}
//returns the weight entry in Kilos or nil if no data
func bodyMassKg(completion: @escaping ((_ bodyMass: Double?, _ date: Date?) -> Void)) {
let query = HKSampleQuery(sampleType: bodyMassType, predicate: nil, limit: 1, sortDescriptors: nil) { (query, results, error) in
if let result = results?.first as? HKQuantitySample {
let bodyMassKg = result.quantity.doubleValue(for: HKUnit.gramUnit(with: .kilo))
completion(bodyMassKg, result.endDate)
return
}
//no data
completion(nil, nil)
}
healthStore.execute(query)
}
}
To get the weight entry from health kit:
healthstore.authorizeHealthKit { (success, error) in
if success {
//get weight
self.healthstore.bodyMass(completion: { (bodyMass, bodyMassDate) in
if bodyMass != nil {
print("bodyMass: \(bodyMass) date: \(bodyMassDate)")
}
})
}
}
回答1:
Your query currently doesn't specify any sort descriptors. You'll need to specify sort descriptors in order to get the query results in the order you expect. You can read more about them in the HKSampleQuery
documentation.
回答2:
Thanks to @Allan answer, I return the last recorded entry by specifying a sortDescriptor:
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let query = HKSampleQuery(sampleType: bodyMassType, predicate: nil, limit: 1, sortDescriptors: [sortDescriptor]) { (query, results, error) in
...
}
来源:https://stackoverflow.com/questions/45046974/how-to-get-the-most-recent-weight-entry-from-healthkit-data