'Getting error while fetching 'HKUnit.kilocalorie' HealthKit

I have a problem to fetching calories with HKUnit.kilocalorie(). But step count is coming perfect and working well. Only kilocalories getting crashed and blank. I tried too many time's according to apple documentation but no success found.

Here is the crash :- 'Attempt to convert incompatible units: count, kcal'

    override func viewDidLoad() {
    super.viewDidLoad()
    //MARK: Get Healthkit permission
    HealthKitAssistant.shared.getHealthKitPermission { (response) in
        self.loadMostRecentSteps()
      }
    }


   func loadMostRecentSteps()  {
    
    guard let stepsdata = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned) else { return }
    
    HealthKitAssistant.shared.getMostRecentStep(for: stepsdata) { (steps , stepsData) in
        self.todayStep = steps
        self.stepDataSource = stepsData
        print(stepsData)
        DispatchQueue.main.async {
            self.labelToday.text = "\(self.todayStep)"
         }
     }

  }


    func getMostRecentStep(for sampleType: HKQuantityType, completion: @escaping (_ stepRetrieved: Int, _ stepAll : [[String : String]]) -> Void) {
    let mostRecentPredicate =  HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options: .strictStartDate)
    var interval = DateComponents()
    interval.day = 1
    let stepQuery = HKStatisticsCollectionQuery(quantityType: sampleType , quantitySamplePredicate: mostRecentPredicate, options: .cumulativeSum, anchorDate: Date.distantPast, intervalComponents: interval)
    stepQuery.initialResultsHandler = { query, results, error in
        if error != nil {
            //  Something went Wrong
            return
        }
        if let myResults = results {
            var stepsData : [[String:String]] = [[:]]
            var steps : Int = Int()
            var cal :Int = Int()
            stepsData.removeAll()
            myResults.enumerateStatistics(from: Date.distantPast, to: Date()) {
                statistics, stop in
                if let quantity = statistics.sumQuantity() {
                    
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "MMM d, yyyy"
                    dateFormatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX") as Locale?
                    dateFormatter.timeZone = NSTimeZone.local
                    var tempDic : [String : String]?
                    let endDate : Date = statistics.endDate
                    steps = Int(quantity.doubleValue(for: HKUnit.count()))
                    cal = Int(quantity.doubleValue(for: HKUnit.kilocalorie()))
                    tempDic = [
                        "enddate" : "\(dateFormatter.string(from: endDate))",
                        "steps"   : "\(steps)",
                        "cal": "\(cal)"
                    ]
                    stepsData.append(tempDic!)
                }
            }
            completion(steps, stepsData.reversed())
        }
    }
    HKHealthStore().execute(stepQuery)
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source