[英]How to get and update height in Healthkit in swift 3?
我试图从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)")
})
}
现在,如果您想读取和写入重量,那么只需使用
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
注意:不要忘记添加这些权限
隐私 - 健康更新用法说明
隐私 - 健康共享使用说明
希望这对仍在搜索它的人有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.