如果您是在Xcode 13.3中开发HealthKit应用程序,而且授权不起作用,您可能需要确保您的代码在正确的线程上运行,并且已经请求了所需的权限。以下例子演示如何启用HealthKit的步数权限:
import HealthKit
let healthStore = HKHealthStore()
func requestAuthorization() {
let steps = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
let typesToShare: Set = [steps]
let typesToRead: Set = [steps]
healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { (success, error) in
if success {
print("Steps authorization succeeded!")
} else {
print("Steps authorization failed: \(error?.localizedDescription ?? "Unknown error")")
}
}
}
在这个例子中,requestAuthorization函数请求步数类型的权限。它使用HKHealthStore实例执行请求,并且在成功或失败后调用闭包来打印消息,以便您可以调试任何错误。
如果您使用类似的代码,但仍然无法成功请求HealthKit权限,请确保您的应用程序配置文件(.plist)中包含所需的键-值对。具体而言,您需要包含NSHealthShareUsageDescription和NSHealthUpdateUsageDescription键,它们分别描述了您需要读取和写入哪些HealthKit数据类型的目的。
NSHealthShareUsageDescription
Our app needs access to your Health data to track your progress.
NSHealthUpdateUsageDescription
Our app needs access to your Health data to write your progress.
如果您已经添加了这些键,并且仍然无法正常工作,请确保在开发设备上审核您的应用程序,并查看系统设置>隐私>
上一篇:AppleHealthKitHKHealthStore.requestAuthorization()返回错误
下一篇:AppleHealthKit,Swift5,iOS中,一个特定的用户能否通过代码访问其他用户的HealthData?