如何从HealthKit获取体脂百分比数据



我正在尝试为自己创建一个小部件,这样我就可以在屏幕上看到我的测量结果。

我成功地从HealthKit获取了身体质量和身体质量指数数据,但我的代码无法获取身体脂肪百分比数据。

在我的搜索中找不到任何关于身体脂肪百分比的信息,所以我想问我是否需要使用不同的方法来获取它的数据?

获取数据的功能:

class func getMostRecentSample(for sampleType: HKSampleType,
completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) {

let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
end: Date(),
options: .strictEndDate)

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

let limit = 1
// This step won't execute as usual while working for Body Fat Percentage data; 
let sampleQuery = HKSampleQuery(sampleType: sampleType,
predicate: mostRecentPredicate,
limit: limit,
sortDescriptors: [sortDescriptor]) { (query, samples, error) in

DispatchQueue.main.async {

guard let samples = samples,
let mostRecentSample = samples.first as? HKQuantitySample else {

completion(nil, error)
return
}

completion(mostRecentSample, nil)
}
}
HKHealthStore().execute(sampleQuery) // then jumps to here.
}

从提取的数据中获取字符串的函数:

class func getSamples(for sampleType: HKSampleType,
unit: HKUnit,
completion: @escaping (String?, Error?) -> Swift.Void) {



getMostRecentSample(for: sampleType) {(sample, error) in
guard let sample = sample else {
return
}

let BMI = String(sample.quantity.doubleValue(for: unit))
// let weight = String(sample.quantity.doubleValue(for: unit))
// let fatPercentage = String(sample.quantity.doubleValue(for: unit))

completion(BMI, nil)
}
}

将数据发送到Timeline,然后预览:

func getTimeline(in context: Context, completion: @escaping (Timeline<WeightEntry>) -> Void) {
let currentDate = Date()
let refreshDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!
guard   let bodyMass = HKObjectType.quantityType(forIdentifier: .bodyMass),
let bodyMassIndex = HKObjectType.quantityType(forIdentifier: .bodyMassIndex),
let bodyFatPercentage = HKObjectType.quantityType(forIdentifier: .bodyFatPercentage) else {
return
}
ProfileDataStore.getSamples(for: bodyMassIndex,unit: HKUnit.count()) { (sample, error) in
guard let sample = sample else {
return
}

let entry = WeightEntry(date: currentDate, value: sample)

let timeline = Timeline(entries: [ entry ], policy: .after(refreshDate))
completion(timeline)
}
}

你作为体脂通过哪个单位?应该是百分比。

最新更新