【问题标题】:How to get the most recent Weight entry from HealthKit data如何从 HealthKit 数据中获取最新的体重条目
【发布时间】:2017-07-12 01:43:41
【问题描述】:

如何从 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)")
            }
        })

    }
}

【问题讨论】:

    标签: ios swift healthkit


    【解决方案1】:

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

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

    【讨论】:

    • 这会从最近记录的体重开始吗?
    【解决方案2】:

    您的查询当前未指定任何排序描述符。您需要指定排序描述符才能按您期望的顺序获取查询结果。你可以在HKSampleQuerydocumentation阅读更多关于它们的信息。

    【讨论】:

    • 谢谢。我以为一旦返回就对结果进行排序,但不是这样,它在返回结果之前排序。
    猜你喜欢
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2017-02-08
    相关资源
    最近更新 更多