获取时会出现错误' hkunit.kilocalorie' HealthKit

发布于 2025-01-28 12:19:31 字数 2901 浏览 2 评论 0原文

我有一个问题来用 hkunit.kilocalorie()获取卡路里。但是,步骤数的完美效果,运行良好。只有千瓦时崩溃和空白。根据Apple文档,我尝试了太多时间,但找不到成功。

这是崩溃: - '尝试转换不相容的单元: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)
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文