如何检查HealthKit是否已被授权

我想检查HeathKit是否已经被授权阅读用户的数据,如果我被授权继续锻炼,如果没有popup警报。 但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并打开它的枚举值,但有同样的问题,我总是被授权。

你在这方面误解了success标志的含义。 如果success则意味着iOS成功向用户询问了健康工具包的访问权限。 这并不意味着他们以“是”回答了这个问题。

要确定他们是否说是/否,您需要得到更具体的信息,如果您有权读取/写入您感兴趣的特定types的数据,请询问保健箱。从HealthKit上的苹果文档:

请求授权后,您的应用程序已准备好访问HealthKit商店。 如果您的应用程序具有共享数据types的权限,则可以创build并保存该types的示例。 您应该通过调用authorizationStatusForTypevalidation您的应用程序是否有权共享数据:在尝试保存任何示例之前。

这里是一个在HealthKitStore中请求和检查权限访问的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) } } })