sss*_*sss 3 ios healthkit swift3
我正在尝试从Healthkit获取和更新高度,但没有获取任何有关swift 3的文档。
有什么方法可以从healthKit获取高度,也可以更新healthKit中的高度吗?
创建一个Healthkit实例
let healthKitStore:HKHealthStore = HKHealthStore()
Run Code Online (Sandbox Code Playgroud)
请求权限
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 )
}
}
Run Code Online (Sandbox Code Playgroud)
阅读高度
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)
Run Code Online (Sandbox Code Playgroud)
书写高度
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)")
})
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您想读写体重,那就用
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
Run Code Online (Sandbox Code Playgroud)
注意:不要忘记添加这些权限
隐私-运行状况更新使用情况说明
隐私-健康共享使用说明
希望这对仍在寻找它的其他人有所帮助
| 归档时间: |
|
| 查看次数: |
1398 次 |
| 最近记录: |