如何检查 HealthKit 是否被授权

How to Check if HealthKit has been authorized

我想检查 HeathKit 是否已被授权让我读取用户数据,如果我被授权继续进行锻炼,如果没有则弹出警报。但是 requestAuthorizationToShareTypes 似乎总是 return 是真的?我怎样才能知道用户是否已经授权我?

override func viewDidLoad() {
        super.viewDidLoad()

        //1. Set the types you want to read from HK Store
        let healthKitTypesToRead: [AnyObject?] = [
            HKObjectType.workoutType()
        ]


        //2. If the store is not available (for instance, iPad) return an error and don't go on.

        if !HKHealthStore.isHealthDataAvailable() {
            let error = NSError(domain: "com.myndarc.myrunz", code: 2, userInfo: [NSLocalizedDescriptionKey: "HealthKit is not available in this Device"])
                print(error)

            let alertController = UIAlertController(title: "HealthKit Not Available", message: "It doesn't look like HealthKit is available on your device.", preferredStyle: .Alert)
            presentViewController(alertController, animated: true, completion: nil)
            let ok = UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in  })
            alertController.addAction(ok)
                    }

        //3. Request Healthkit Authorization

        let sampleTypes = Set(healthKitTypesToRead.flatMap { [=10=] as? HKSampleType })

        healthKitStore.requestAuthorizationToShareTypes(sampleTypes, readTypes: nil) {

            (success, error) -> Void in

            if success {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                                                        self.performSegueWithIdentifier("segueToWorkouts", sender: nil)
                                                    });
            } else {
                print(error)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                                        self.showHKAuthRequestAlert()
                                    });
            }

        }
    }

或者,我已经尝试过 authorizationStatusForType 并打开它的枚举值,但是我遇到了同样的问题,因为我总是被授权。

您误解了 success 标志在此上下文中的含义。 当 success 为真时,这意味着 iOS 成功询问了用户有关健康工具包的访问权限。这并不意味着他们用 'yes'.

回答了那个问题

要确定他们是否说 yes/no,您需要更具体,并询问 health kit 您是否有权 read/write 您感兴趣的特定类型的数据。 来自 HealthKit 上的苹果文档:

After requesting authorization, your app is ready to access the HealthKit store. If your app has permission to share a data type, it can create and save samples of that type. You should verify that your app has permission to share data by calling authorizationStatusForType: before attempting to save any samples.

Note: authorizationStatus is to determine the access status only to write but not to read. There is no option to know whether your app has read access. FYI,

这里是在HealthKitStore

中请求和检查权限访问的示例
// Present user with items we need permission for in HealthKit
healthKitStore.requestAuthorization(toShare: typesToShare, read: typesToRead, completion: { (userWasShownPermissionView, error) in

    // Determine if the user saw the permission view
    if (userWasShownPermissionView) {
        print("User was shown permission view")

        // ** IMPORTANT
        // Check for access to your HealthKit Type(s). This is an example of using BodyMass.
        if (self.healthKitStore.authorizationStatus(for: HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!) == .sharingAuthorized) {
            print("Permission Granted to Access BodyMass")
        } else {
            print("Permission Denied to Access BodyMass")
        }

    } else {
        print("User was not shown permission view")

        // An error occurred
        if let e = error {
            print(e)
        }
    }
})

目前,应用程序无法确定用户是否已授予读取健康数据的权限。

以下是 Apple 来自 authorizationStatus(for:) 的描述:

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. If your app is given share permission but not read permission, you see only the data that your app has written to the store. Data from other sources remains hidden.