如何检查是否已授权 HealthKit

26

我希望能够检查是否已经授权HeathKit让我读取用户数据。如果我被授权,则转到锻炼页面,否则弹出警报。但是requestAuthorizationToShareTypes似乎总是返回true?我该如何获取用户是否授权我所需的参考?

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 { $0 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并打开了它的枚举值,但是遇到了同样的问题,即我始终被授权。


系统从未询问过您的权限吗? - Julian
不仅如此,即使您未授权,成功块也会被调用。 - GarySabo
3个回答

20
您误解了此上下文中success标志的含义。当success为true时,这仅表示iOS已成功询问用户是否允许访问健康工具包。这并不意味着他们以“是”或“否”的方式回答了该问题。
要确定他们是否同意或拒绝,您需要更加具体,并询问健康工具包是否允许您读取/写入您感兴趣的特定类型的数据。从Apple关于HealthKit的文档中可以了解到:
“在请求授权之后,您的应用程序已准备好访问HealthKit存储。如果您的应用程序具有共享数据类型的权限,则可以创建和保存该类型的样本。在尝试保存任何样本之前,请通过调用authorizationStatusForType:验证您的应用程序是否有共享数据的权限。”

4
谢谢...我确实尝试了authorizationStatusForType,但据我所知,我无法读取此内容:https://dev59.com/gV8e5IYBdhLWcg3wqryt - GarySabo
2
苹果非常关注用户的隐私,如果您没有获得权限,那么在 HealthKit 存储中请求类型的数据似乎就不存在。如果您的应用程序被授予共享权限但没有读取权限,则只能看到您的应用程序写入存储的数据。来自其他来源的数据仍然是隐藏的。 - Ash

15

注意:authorizationStatus仅用于确定写入的访问状态,而不是读取的访问状态。没有选项可以知道您的应用程序是否具有读取权限。请参阅此链接

这里有一个在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)
        }
    }
})

requestAuthorization 函数会展示授权视图... 这不是在 检测 - User
8
我已经开启了读写权限,但是authorizationStatus始终返回false。 - Drunken Daddy
@SarathNagesh,你有没有找到每次都是false的解决方法?我也遇到了同样的问题。如果你有解决方案,请分享一下。我已经浪费了一整天的时间。 - Chetan Prajapati

13

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

以下是苹果公司在authorizationStatus(for:)中的描述:

为了帮助防止敏感健康信息可能泄漏,您的应用程序不能确定用户是否授权读取数据。如果您没有获得授权,则看起来好像 HealthKit 存储中没有请求类型的任何数据。如果您的应用程序被授予共享权限但未被授予读取权限,则只能查看您的应用程序已写入存储器的数据。来自其他来源的数据将保持隐藏。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接