如何从HealthKit数据中获取最新的Weight项

时间:2017-07-12 01:43:42

标签: ios swift health-kit

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

    }
}

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

您的查询当前未指定任何排序描述符。您需要指定排序描述符,以便按照您期望的顺序获取查询结果。您可以在HKSampleQuery documentation

中详细了解它们