簡體   English   中英

如何從HealthKit數據中獲取最新的Weight項

[英]How to get the most recent Weight entry from HealthKit data

如何從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
        ...
    }

您的查詢當前未指定任何排序描述符。 您需要指定排序描述符,以便按照您期望的順序獲取查詢結果。 您可以在HKSampleQuery 文檔中閱讀有關它們的HKSampleQuery 信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM