HealthKit请求授权:为什么结果总是成功?

Requesting authorization in HealthKit: why the result is always successful?

我请求访问某些健康信息只是为了以这种方式阅读:

let healthStore = HKHealthStore()
let types: Set<HKObjectType> = [distanceWalkingRunning]

healthStore.requestAuthorization(toShare: nil, read: types) { (success, error) in
        completion(success, error)
}

然后,当第一次启动该应用程序时,我看到了标准对话框以选择是否允许 Health 访问信息。如果我点击 "Don't Allow",则会显示警告视图:

Health Access - You can turn on health data categories later in the Health app.

他们,警报和健康访问对话框都被关闭,并显示应用程序的登录屏幕。我可以看到 healthStore.requestAuthorization 方法调用中提供的 completion 闭包正在为 success 参数获取 true 值,为 [=16= 获取 nil ] 无论如何争论。

我怎么知道用户不允许访问健康?

success 参数的 documentation 为:

A Boolean value that indicates whether the request was processed successfully. This value does not indicate whether permission was actually granted. This parameter is false if an error occurred while processing the request; otherwise, it is true.

在初始请求和后续请求中,请求均已成功处理,您获得 true for success

您无法查明用户是否已授予对您请求的数据的读取权限。同样,来自 the documentation:

To help prevent possible leaks of sensitive health information, your app cannot determine whether or not a user has granted permission to read data. If you are not given permission, it simply appears as if there is no data of the requested type in the HealthKit store.

提交授权请求后,您只需尝试读取数据,您就会获得数据,否则似乎没有可用数据。