如何从HealthKit数据中获取最新的体重条目 [英] How to get the most recent Weight entry from HealthKit data

查看:139
本文介绍了如何从HealthKit数据中获取最新的体重条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Healthkit数据中获取最新的体重记录?

How can I get the most recent weight entry from healthkit data?

我的代码仅返回有史以来记录的第一个重量记录.

My code is only returning the first weight entry ever recorded.

是否可以仅记录最后记录而无需指定日期范围?

这是我的代码获得第一个条目:

Here is my code that gets the first entry:

class HealthStore {

    private let healthStore = HKHealthStore()
    private let bodyMassType = HKSampleType.quantityType(forIdentifier: .bodyMass)!

    func authorizeHealthKit(completion: @escaping ((_ success: Bool, _ error: Error?) -> Void)) {

        if !HKHealthStore.isHealthDataAvailable() {
            return
        }

        let readDataTypes: Set<HKSampleType> = [bodyMassType]

        healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) in
            completion(success, error)
        }

    }


    //returns the weight entry in Kilos or nil if no data
    func bodyMassKg(completion: @escaping ((_ bodyMass: Double?, _ date: Date?) -> Void)) {

        let query = HKSampleQuery(sampleType: bodyMassType, predicate: nil, limit: 1, sortDescriptors: nil) { (query, results, error) in
            if let result = results?.first as? HKQuantitySample {
                let bodyMassKg = result.quantity.doubleValue(for: HKUnit.gramUnit(with: .kilo))
                completion(bodyMassKg, result.endDate)
                return
            }

            //no data
            completion(nil, nil)
        }
        healthStore.execute(query)
    }

}

要从医疗工具包中获取重量输入:

To get the weight entry from health kit:

healthstore.authorizeHealthKit { (success, error) in
    if success {

        //get weight
        self.healthstore.bodyMass(completion: { (bodyMass, bodyMassDate) in
            if bodyMass != nil {
                print("bodyMass: \(bodyMass)   date: \(bodyMassDate)")
            }
        })

    }
}

推荐答案

您的查询当前未指定任何排序描述符.您需要指定排序描述符,以便按期望的顺序获取查询结果.您可以在HKSampleQuery 文档中了解更多信息.

Your query currently doesn't specify any sort descriptors. You'll need to specify sort descriptors in order to get the query results in the order you expect. You can read more about them in the HKSampleQuery documentation.

这篇关于如何从HealthKit数据中获取最新的体重条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆