在AppleHealthKit中,用户需要授权应用程序才能访问其健康数据。因此,只有授权应用程序才能访问用户的HealthData,其他应用程序无法访问。
以下是一个示例,展示如何使用Swift5和HealthKit API获取特定用户的身体质量指数(Body Mass Index):
import HealthKit
// 获取HealthKit权限
let healthStore = HKHealthStore()
let bmiQuantity = HKQuantityType.quantityType(forIdentifier: .bodyMassIndex)!
healthStore.requestAuthorization(toShare: nil, read: [bmiQuantity]) { (success, error) in
if let error = error {
print("Error requesting health store authorization: \(error.localizedDescription)")
return
}
if success {
// 获取当前用户的身体质量指数
let calendar = Calendar.current
let now = Date()
let components = calendar.dateComponents([.year, .month, .day], from: now)
guard let startDate = calendar.date(from: components) else {
print("Error creating start date")
return
}
guard let endDate = calendar.date(byAdding: .day, value: 1, to: startDate) else {
print("Error creating end date")
return
}
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let query = HKSampleQuery(sampleType: bmiQuantity, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (query, results, error) in
if let error = error {
print("Error fetching body mass index: \(error.localizedDescription)")
return
}
if let bmiSamples = results as? [HKQuantitySample] {
if let mostRecentBmi = bmiSamples.first {
let bmiUnit = HKUnit.count().unitDivided(by: HKUnit.meter().unitSquared())
let bmi = most
上一篇:AppleHealthKit授权无法正常工作(Xcode13.3)-在请求授权时失败
下一篇:Apple会在2022年开始强制要求企业使用ABM分发或其他分发方式,而不再支持使用IOS企业分发账号进行内部分发吗?