Vote count: 0
I'm trying to read user's steps count of last 7 days from HealthKit datas and write a dictionary with [date: steps]. The code to calculate the date is correct, the code read steps is correct, but, together, they return wrong datas (they read steps just for a day, and count is wrong...).
Here's the code:
let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
let dataTypesToRead = NSSet(object: stepsCount!)
healthStore?.requestAuthorization(toShare: dataTypesToRead as? Set<HKSampleType>, read: dataTypesToRead as? Set<HKObjectType>, completion: { (success, error) in if success { print("SUCCESS") } else { print("ERROR") } })
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
var startDate = NSCalendar.current.startOfDay(for: NSDate() as Date)
var components = DateComponents(); components.day = 1; components.second = -1
var endDate = NSCalendar.current.date(byAdding: components, to: startDate, wrappingComponents: false)!
for _ in (0 ..< 7) {
startDate = NSCalendar.current.date(byAdding: .day, value: -1, to: startDate)!
endDate = NSCalendar.current.date(byAdding: .day, value: -1, to: endDate)!
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictEndDate)
let query = HKStatisticsQuery(quantityType: quantityType!, quantitySamplePredicate: predicate, options: [.cumulativeSum, .separateBySource]) {query, results, error in
if results != nil {
print(results!)
if let quantity = results?.sumQuantity() {
self.stepCountComplete.updateValue(quantity.doubleValue(for: HKUnit.count()), forKey: endDate)
}
}
}
self.healthStore?.execute(query)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { print(self.stepCountComplete) }
Where am I wrong?
asked 32 secs ago
Difficulties reading datas user's steps count with HealthKit
Aucun commentaire:
Enregistrer un commentaire