【发布时间】:2016-11-18 10:09:12
【问题描述】:
我正在尝试从 Healthkit 获取和更新高度,但没有获取 swift 3 的任何文档。
有没有什么方法可以从 healthKit 中获取高度来更新 healthKit 中的高度?
【问题讨论】:
-
你找到解决办法了吗?
-
我也有同样的问题
我正在尝试从 Healthkit 获取和更新高度,但没有获取 swift 3 的任何文档。
有没有什么方法可以从 healthKit 中获取高度来更新 healthKit 中的高度?
【问题讨论】:
创建一个 healthkit 实例
let healthKitStore:HKHealthStore = HKHealthStore()
请求权限
func requestPermissions(completion: @escaping ((_ success:Bool, _ error:Error?) -> Void)){
let healthKitTypesToRead : Set<HKSampleType> = [
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!,
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
]
let healthKitTypesToWrite: Set<HKSampleType> = [
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!,
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
]
if !HKHealthStore.isHealthDataAvailable() {
print("Error: HealthKit is not available in this Device")
completion(false, error)
return
}
healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in
completion(success,error )
}
}
阅读高度
let heightType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!
let query = HKSampleQuery(sampleType: heightType, predicate: nil, limit: 1, sortDescriptors: nil) { (query, results, error) in
if let result = results?.first as? HKQuantitySample{
print("Height => \(result.quantity)")
}else{
print("OOPS didnt get height \nResults => \(results), error => \(error)")
}
}
self.healthKitStore.execute(query)
书写高度
let height = YOUR_HEIGHT
if let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) {
let date = Date()
let quantity = HKQuantity(unit: HKUnit.inch(), doubleValue: height!)
let sample = HKQuantitySample(type: type, quantity: quantity, start: date, end: date)
self.healthKitStore.save(sample, withCompletion: { (success, error) in
print("Saved \(success), error \(error)")
})
}
现在,如果您想读写 Weight,那么只需使用
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
注意:不要忘记添加这些权限
隐私 - 健康更新使用说明
隐私 - Health Share 使用说明
希望这对仍在寻找它的其他人有所帮助
【讨论】: