Home > front end >  Does apple healthkit queries run asynchronously?
Does apple healthkit queries run asynchronously?

Time:01-03

Does the apple healthkit queries like HKStatisticsQuery, HKSampleQuery and HKStatisticsCollectionQuery run asynchronously or do we need to explicitly run the queries in a separate thread ?

I just wrote the queries using any async way as follows and it works. I want to know whether I should put it inside an async block

private func readOxygrnSaturation(){
        dispatchGroup.enter()
        let quantityType  = HKObjectType.quantityType(forIdentifier: .oxygenSaturation)!
        let sampleQuery = HKSampleQuery.init(sampleType: quantityType,
                                             predicate: nil,
                                             limit: HKObjectQueryNoLimit,
                                             sortDescriptors: nil,
                                             resultsHandler: { (query, results, error) in
            
            guard let samples = results as? [HKQuantitySample] else {
                print(error!)
                return
            }
            for sample in samples {
                let mSample = sample.quantity.doubleValue(for: HKUnit(from: "%"))
                self.oxygenSaturation.append(HealthData(unit: "%", startDate: self.dateFormatter.string(from: sample.startDate) , endDate: self.dateFormatter.string(from: sample.endDate), value: mSample))
            }
            self.dispatchGroup.leave()
        })
        self.healthStore .execute(sampleQuery)
        
    }

CodePudding user response:

On iOS, HealthKit queries are run asynchronously. You do not need to run them in a separate thread.

To perform a HealthKit query, you will create an HKQuery object and then call the HKHealthStore method execute(_:) to execute the query. This method returns immediately, and the results of the query are returned to you through a completion handler that you provide.

Here is an example of how to execute an HKStatisticsQuery:

    let healthStore = HKHealthStore()

let query = HKStatisticsQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (query, result, error) in
    guard let result = result, let sum = result.sumQuantity() else {
        // handle the error
        return
    }

    // use the result
}

healthStore.execute(query)

This code creates an HKStatisticsQuery object and then executes it by calling the execute(_:) method of HKHealthStore. The completion handler is provided as a closure to the HKStatisticsQuery initializer, and it is called when the query finishes executing.

  • Related