joffd
joffd

Reputation: 531

Func returning before second healthkit query complete

I am trying to get both stepsQuantityType and kjActiveQuantityType for a given date from HealthKit.

I can get both queries to work if fun separately but when trying to run them together in the same function the ruction returns before the second query is complete giving an index out of range error as index 1 of the array has not been filled.

Any help would be greatly appreciated.

i call the func using

getTodaysStepsAndKJ { arrayData in
            self.stepsHolder = arrayData[0]
            self.kjHolder = arrayData[1] * 4.184
            DispatchQueue.main.async {self.stepsLabel.text = arrayData[0].description;
                                      self.kjLabel.text = (arrayData[1] * 4.184).description}
            self.saveDataToCloud()
        }

and the func is

func getTodaysStepsAndKJ(completion: @escaping (Array<Double>) -> Void) {
      let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
      let kjActiveQuantityType = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!
      var resultArray = Array<Double>();
      let now = Date()
      let startOfDay = Calendar.current.startOfDay(for: now)
      let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

      let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
          guard let result = result, let sum = result.sumQuantity() else {
            resultArray.insert(0.0, at: 0)
            completion(resultArray)
              return
          }
        resultArray.insert(sum.doubleValue(for: HKUnit.count()), at: 0)
          completion(resultArray)

      }
        let query2 = HKStatisticsQuery(quantityType: kjActiveQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
            guard let result = result, let sum = result.sumQuantity() else {
                resultArray.insert(0.0, at: 1)
                completion(resultArray)
                return
            }
            resultArray.insert(sum.doubleValue(for: HKUnit.kilocalorie()), at: 1)
            completion(resultArray)
        }
    healthStore.execute(query)
    healthStore.execute(query2)
  }

When split and run as two functions they both work fine.

Upvotes: 0

Views: 137

Answers (1)

Jawad Ali
Jawad Ali

Reputation: 14397

if you take query2 inside query one ... then it can work .. roughly something like following ...not tested code

func getTodaysStepsAndKJ(completion: @escaping (Array<Double>) -> Void) {
      let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
      let kjActiveQuantityType = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!
      var resultArray = Array<Double>();
      let now = Date()
      let startOfDay = Calendar.current.startOfDay(for: now)
      let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

      let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
          guard let result = result, let sum = result.sumQuantity() else {
            resultArray.insert(0.0, at: 0)
            completion(resultArray)
              return
          }
        resultArray.insert(sum.doubleValue(for: HKUnit.count()), at: 0)
           let query2 = HKStatisticsQuery(quantityType: kjActiveQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
            guard let result = result, let sum = result.sumQuantity() else {
                resultArray.insert(0.0, at: 1)
                completion(resultArray)
                return
            }
            resultArray.insert(sum.doubleValue(for: HKUnit.kilocalorie()), at: 1)
            completion(resultArray)
        }
      healthStore.execute(query2)
      }

    healthStore.execute(query)

  }

Upvotes: 1

Related Questions