我正试图从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)
注意:不要忘记添加这些权限
隐私-运行状况更新使用说明
隐私-运行状况共享使用说明
希望这对那些仍在寻找它的人有帮助