The number 0 is being returned every time in HealthKit using swift?

266 views Asked by At

I have been successfully able to write to HealthKit but receiving these values always return 0. I am trying to return the latest value of weight.

This is the function that I read weight:

public func readWeight(result: @escaping (Double) -> Void) {
    print("Weight")
    let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)

    let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {

        query, results, error in

        if (error != nil) {
            print(error!)
            result(0.0)
        }

        guard let results = results else {
            print("No results of query")
            result(0.0)
            return
        }

        if (results.count == 0) {
            print("Zero samples")
            result(0.0)
            return
        }

        guard let bodymass = results[0] as? HKQuantitySample else {
            print("Type problem with weight")
            result(0.0)
            return
        }
        result(bodymass.quantity.doubleValue(for: HKUnit.pound()))
    }

    healthKitStore.execute(weightQuery)
}

This is how I set it to a variable:

 readWeight() { weight in
     Weight = weight
 }

Thanks!

1

There are 1 answers

0
Johnd On

If I understand your question correctly, you are declaring your variable bodymass as the very first element in the array results[0], it must be the last element of the array. Check if your first value for weight is 0 in the Health app, it most likely is because as I said bodymass is the first element of results or your first value in the Health app. Hope this helps.