I have already created a function to fetch active energy data from HealthKit. But if I try to fetch records of 1 year with multiple active energy records per day, the app hangs and in some cases App does crash and I don't get any data.
I couldn't find any other way to access the summary day values for Active Energy from Apple HealthKit.
Below is my code for getting Active Energy from HealthKit.
HealthKitSetupManager.swift
I couldn't find any other way to access the summary day values for Active Energy from Apple HealthKit.
Below is my code for getting Active Energy from HealthKit.
Code Block func getActiveEnergy(startDate : Date) { var startingDate = startDate HealthKitSetupManager.getActiveEnergy(date: startDate, withSuccess: { (isSuccess, error) in if isSuccess { print("Active Energy Fetch") } startingDate = NSCalendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date() if startingDate <= Date() { self.getActiveEnergy(startDate: startingDate) } else { self.getSickNumber(startDate : self.globalDate) } }) }
HealthKitSetupManager.swift
Code Block class func getActiveEnergy(date:Date, withSuccess: @escaping(Bool,String?) -> Void) { let healthKitStore = HKHealthStore() if let energyType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned) { let calendar = NSCalendar.current var components = DateComponents() components.day = 1 let eDateString = date.getFormattedString(format: DateFormateString.MM_dd_yyyy) let eDate = eDateString.getFormattedDate(inFormate: DateFormateString.MM_dd_yyyy) ?? Date() let endDate = calendar.date(byAdding: components, to: eDate) ?? Date() let predicate = HKQuery.predicateForSamples(withStart: date, end: endDate, options: .strictStartDate) let updateHandler = HKStatisticsQuery(quantityType: energyType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (query, sample, error) -> Void in if error != nil { withSuccess(false,error?.localizedDescription ?? "") return } if let sample = sample { let energy = sample.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0.0 print(endDate, "->", energy) withSuccess(true, nil) return } else { withSuccess(false, nil) return } } healthKitStore.execute(updateHandler) } }