• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何从 HealthKit 中获取与 Health App 的值相同的静息能量值?

[复制链接]
菜鸟教程小白 发表于 2022-12-11 20:04:47 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在使用苹果的 HealthKit sample但是,iPhone 中 Health app 中显示的 resting energy 值与示例应用中获取的值不匹配。

根据苹果文档,HKQuantityTypeIdentifierBasalEnergyBurned 代表 resting energy 所以我从 HealthKit 中获取了这个值,但我收到的值与 resting 不匹配健康应用中显示的能量

于是我偶然发现了苹果的HealthKit sample他们根据公式计算静息能量:

// Calculates the user's total basal (resting) energy burn based off of their height, weight, age,
    // and biological sex. If there is not enough information, return an error.
    private func fetchTotalBasalBurn(completion: @escaping (HKQuantity?, Error?) -> Void)
    {
        let todayPredicate: NSPredicate = self.predicateForSamplesToday()

        let weightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!
        let heightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!

        let queryWeigth: HKCompletionHandle = {
            (weight, error) -> Void in

            guard let weight = weight else {
                completion(nil, error)

                return
            }

            let queryHeigth: HKCompletionHandle = {
                (height, error) -> Void in

                if height == nil {
                    completion(nil, error)

                    return;
                }

                var dateOfBirth: Date!

                do {

                    dateOfBirth = try self.healthStore!.dateOfBirth()

                } catch {

                    completion(nil, error)

                    return
                }

                var biologicalSexObjet: HKBiologicalSexObject!

                do {

                    biologicalSexObjet = try self.healthStore!.biologicalSex()

                } catch {

                    completion(nil, error)

                    return
                }

                // Once we have pulled all of the information without errors, calculate the user's total basal energy burn
                let basalEnergyButn: HKQuantity? = self.calculateBasalBurnTodayFromWeight(weight, height: height, dateOfBirth: dateOfBirth!, biologicalSex: biologicalSexObjet)

                completion(basalEnergyButn, nil)
            }

            if let healthStore = self.healthStore {

                healthStore.mostRecentQuantitySample(ofType: heightType, predicate: todayPredicate, completion: queryHeigth)
            }
        }

        if let healthStore = self.healthStore {
            healthStore.mostRecentQuantitySample(ofType: weightType, predicate: nil, completion: queryWeigth)
        }
    }

    private func calculateBasalBurnTodayFromWeight(_ weight: HKQuantity?, height: HKQuantity?, dateOfBirth: Date, biologicalSex: HKBiologicalSexObject) -> HKQuantity?
    {
        // Only calculate Basal Metabolic Rate (BMR) if we have enough information about the user
        guard let weight = weight, let height = height else {

            return nil
        }

        // Note the difference between calling +unitFromString: vs creating a unit from a string with
        // a given prefix. Both of these are equally valid, however one may be more convenient for a given
        // use case.
        let heightInCentimeters: Double = height.doubleValue(for: HKUnit(from:"cm"))
        let weightInKilograms: Double = weight.doubleValue(for: HKUnit.gramUnit(with: HKMetricPrefix.kilo))

        let nowDate = Date()
        let ageComponents: DateComponents = Calendar.current.dateComponents([Calendar.Component.year], from: dateOfBirth, to: nowDate)
        let ageInYears: Int = ageComponents.year!

        // BMR is calculated in kilocalories per day.
        let BMR: Double = self.calculateBMRFromWeight(weightInKilograms: weightInKilograms, height: heightInCentimeters, age: ageInYears, biologicalSex: biologicalSex.biologicalSex)

        // Figure out how much of today has completed so we know how many kilocalories the user has burned.
        let (startOfToday, endOfToday): (Date, Date) = self.datesFromToday()

        let secondsInDay: TimeInterval = endOfToday.timeIntervalSince(startOfToday)
        let percentOfDayComplete: Double = nowDate.timeIntervalSince(startOfToday) / secondsInDay

        let kilocaloriesBurned: Double = BMR * percentOfDayComplete

        let basalBurn = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: kilocaloriesBurned)

        return basalBurn
    }

/// Returns BMR value in kilocalories per day. Note that there are different ways of calculating the
    /// BMR. In this example we chose an arbitrary function to calculate BMR based on weight, height, age,
    /// and biological sex.
    private func calculateBMRFromWeight(weightInKilograms: Double, height heightInCentimeters: Double, age ageInYears: Int, biologicalSex: HKBiologicalSex) -> Double
    {
        var BMR: Double = 0

        if biologicalSex == .male {
            BMR = 66.0 + (13.8 * weightInKilograms) + (5.0 * heightInCentimeters) - (6.8 * Double(ageInYears))

            return BMR
        }

        BMR = 655 + (9.6 * weightInKilograms) + (1.8 * heightInCentimeters) - (4.7 * Double(ageInYears))

        return BMR
    }

我尝试使用示例应用获取静息能量,但健康应用中显示的静息能量值与示例应用的值不同。

谁能告诉我如何获取静息能量或Health App使用什么计算来找到静息能量

如果有人可以给我一些指示,那就太好了,我对 HealthKit 还是很陌生。

谢谢。



Best Answer-推荐答案


Apple 的示例似乎已过时。从 iOS 8 和 watchOS 2 开始,可以调用检索此信息的方式与检索事件卡路里的方式相同;只需更改标识符。 Apple Documentation

HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.basalEnergyBurned)

不要忘记包含读取此数据的额外权限。

关于ios - 如何从 HealthKit 中获取与 Health App 的值相同的静息能量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003294/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap