我想检查 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 并打开它的枚举值,但是我遇到了同样的问题,因为我总是被授权。
最佳答案
您误解了 success
标志在此上下文中的含义。
当 success
为真时,这意味着 iOS 已成功向用户询问有关健康工具包的访问权限。这并不意味着他们用"is"回答了那个问题。
要确定他们是否说是/否,您需要更具体,并询问 health kit 您是否有权读/写您感兴趣的特定类型的数据。 来自 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.
关于ios - 如何检查 HealthKit 是否被授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33018445/