0

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

Krishan Madushanka
  • 319
  • 1
  • 5
  • 21
  • 1
    The results of the `HKSampleQuery` are only available in the function's closure, which gets executed after the query is complete. So yes, it's asynchronous. From what I can see you use the function as it is supposed to, and you write that it works. If `self.oxygenSaturation` is represented in a View, it would make sense to execute it on `DispatchQueue.main.async`, as it is part of the app's UI. – a_hausb Jan 03 '23 at 09:02
  • 1
    Your use of DispatchGroup here has a serious flaw. Your `guard` can return without leaving the group. Very bad. – HangarRash Jan 04 '23 at 17:04

0 Answers0