-1

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!

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
arodebaugh
  • 538
  • 1
  • 8
  • 26
  • 1
    Possible duplicate of [Get the latest HKSampleQuery datapoint in swift 3?](https://stackoverflow.com/questions/44849723/get-the-latest-hksamplequery-datapoint-in-swift-3) – ninjaproger Jul 07 '17 at 00:24
  • @ninjaproger That is mine... I made it so the question can be a little clearer and it is asked differently – arodebaugh Jul 07 '17 at 00:26
  • @arodebaugh if you have the same problem in both questions, then you you should update the first one to be more clear, not open another open. – Cristik Jul 07 '17 at 11:30
  • @Cristik Made the other one clearer sorry about all this mixup I just really want to continue on this project but this bug is making me unable to do so – arodebaugh Jul 07 '17 at 12:08
  • @arodebaugh if you improved the other question, is this one still needed? You can delete it if not. – Cristik Jul 07 '17 at 16:15

1 Answers1

0

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.

Johnd
  • 584
  • 2
  • 6
  • 21