【发布时间】:2015-10-08 14:18:53
【问题描述】:
我想检查 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 并打开了它的枚举值,但遇到了同样的问题,因为我总是被授权。
【问题讨论】:
-
系统从来没有问过你的权限吗?
-
不会,但是即使你不授权,也会调用成功块