ios - 如何从 HealthKit 数据中获取最新的 Weight 条目

标签 ios swift healthkit

如何从 healthkit 数据中获取最新的体重条目?

我的代码只返回有史以来第一个重量条目。

是否可以在不指定日期范围的情况下仅获取最后记录的条目?

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

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

}

从健康包中获取体重条目:

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

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

    }
}

最佳答案

感谢@Allan 的回答,我通过指定 sortDescriptor 返回最后记录的条目:

    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)

    let query = HKSampleQuery(sampleType: bodyMassType, predicate: nil, limit: 1, sortDescriptors: [sortDescriptor]) { (query, results, error) in
        ...
    }

关于ios - 如何从 HealthKit 数据中获取最新的 Weight 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046974/

相关文章:

ios - 强制 View 在 UIStackView 中占用尽可能多的空间

ios - 在 UILabel 中显示可点击的 URL 和图标

swift - 为什么要编译?在另一个函数中声明的函数

ios - 如何在 addTarget 的操作中传递参数?

ios - NSRange :rangeOfString throws an exception in AFHTTPRequestOperation's success block

ios - Swift - 即使我插入了不同的数字,文本字段也会返回 0

accelerometer - 在 watchOS 2 中关闭屏幕时无法获取加速度计和心率数据

ios - 如何使用 HealthKit 获取特定日期的 24 小时 sleep 数据?

ios - 使用 HKHeartbeatSeriesSample 从 Apple Watch 获取实时心跳数据

ios - 使用 swift 中的按钮操作控制网页 View