HealthKit - requestAuthorization(toShare:read:completion:) 总是成功

2024-02-17

我正在使用 Xcode 8 beta 6,并且请求访问 Health 应用程序。方法requestAuthorization(toShare:read:completion:)请求授权总是会产生一个true当完成处理程序返回时 -success在我下面的代码中。即使我拒绝模拟器中的所有内容,我也会得到一个true。 这是我处理授权的代码。是我的代码有问题还是 Xcode 错误?

import Foundation
import HealthKit

class HealthManager {
    private let healthStore = HKHealthStore()

    class var sharedInstance: HealthManager {
        struct Singleton {
            static let instance = HealthManager()
        }
        return Singleton.instance
    }

    private var isAuthorized: Bool? = false

    func authorizeHealthKit(completion: ((_ success: Bool) -> Void)!) {
        let writableTypes: Set<HKSampleType> = [HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!, HKWorkoutType.workoutType(), HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!, HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!, HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!]
        let readableTypes: Set<HKSampleType> = [HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!, HKWorkoutType.workoutType(), HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!, HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!, HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!]

        guard HKHealthStore.isHealthDataAvailable() else {
            completion(false)
            return
        }

        // Request Authorization
        healthStore.requestAuthorization(toShare: writableTypes, read: readableTypes) { (success, error) in

            if success {
                completion(true)
                self.isAuthorized = true
            } else {
                completion(false)
                self.isAuthorized = false
                print("error authorizating HealthStore. You're propably on iPad \(error?.localizedDescription)")
            }
        }
    }
}

感谢您的帮助!


您误解了成功标志的含义。 YES 表示权限屏幕已成功显示,NO 表示权限屏幕显示时出错。来自苹果的 HealthKit 文档:

一个布尔值,指示请求是否已成功处理。该值并不指示是否实际授予了权限。如果处理请求时发生错误,则该参数为NO;否则,为“是”。

如果你想检查你是否有权写入数据,你需要使用authorizationStatus(for:),但请注意,您无法确定读取数据的授权。

该方法检查保存数据的授权状态。

为了帮助防止敏感健康信息可能泄露,您的应用程序无法确定用户是否已授予读取数据的权限。如果您未获得许可,则看起来好像 HealthKit 存储中没有所请求类型的数据。如果您的应用程序被授予共享权限但没有读取权限,您只能看到您的应用程序已写入商店的数据。来自其他来源的数据仍然隐藏。

文档在这里:https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKHealthStore_Class/index.html https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKHealthStore_Class/index.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HealthKit - requestAuthorization(toShare:read:completion:) 总是成功 的相关文章

随机推荐