Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the most recent Weight entry from HealthKit data

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)")
            }
        })

    }
}
like image 322
George Filippakos Avatar asked Jul 12 '17 01:07

George Filippakos


People also ask

Where is HealthKit data stored?

To quote: This data is stored in Data Protection class Protected Unless Open. Access to the data is relinquished 10 minutes after device locks, and data becomes accessible the next time user enters their passcode or uses Touch ID or Face ID to unlock the device.

Is Apple Health the same as HealthKit?

HealthKit is the developer framework behind it that allows apps to work with Apple Health and each other. If you're confused about how the Apple Health app works, what type of information you need to get the most out of it, and which apps are compatible, keep reading.

How do I access Apple Health data?

To view your goals and your move, exercise, and stand data, open the Health app, tap the Browse tab, then tap Activity. To see your heart rate data, open the Health app, tap the Browse tab, then tap Heart.

How does Apple HealthKit work?

It collects health and fitness data from your iPhone, the built-in sensors on your Apple Watch, compatible third-party devices, and apps that use HealthKit. The Health app is built to keep your data secure and protect your privacy. Your data is encrypted and you are always in control of your health information.


2 Answers

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
        ...
    }
like image 163
George Filippakos Avatar answered Sep 24 '22 15:09

George Filippakos


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.

like image 38
Allan Avatar answered Sep 20 '22 15:09

Allan