IOS 9.2.1, Swift 2.1
I'm trying to give the user a reasonable error message when accessing HealthKit and 0 records are returned for a query.
It could be that there were no records within the selected time range or it could be that the user has disallowed access to that particular dataset inside health. In both case the "storage.requestAuthorizationToShareTypes" provides a "success" value of true.
Is there a way to get the HKHealthKit store give me a code that indicates that the access has been disabled?
My code below
Thanks Mike
import Foundation
import HealthKit
// Interface to the HealthKit
class HealthKitIF {
let storage = HKHealthStore()
var stepsEnabled = false
var bgEnabled = false
var hkSupported = false
init () {
self.checkAuthorization()
}
func checkAuthorization () -> Bool {
// Default to assuming that we're authorized
var isEnabled = true
if (NSClassFromString("HKHealthStore") != nil) { hkSupported = true }
// Do we have access to HealthKit on this device?
if ((hkSupported) && (HKHealthStore.isHealthDataAvailable())) {
// We have to request each data type explicitly
// Ask for BG
var readingsSet = Set<HKObjectType>()
readingsSet.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!)
readingsSet.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)
storage.requestAuthorizationToShareTypes(nil, readTypes: readingsSet) { (success, error) -> Void in
isEnabled = success
self.bgEnabled = success
}
}
else
{
isEnabled = false
}
return isEnabled
}
Your app should not present an error message when there are no results for a query. HealthKit is designed to keep the user's read authorization choices private by not differentiating between unauthorized access and no data. It may, however, be helpful to include a reminder somewhere in your app or on your support pages that describes how the user can adjust their Health privacy settings if they are not seeing expected behavior in your app.
From the HKHealthStore class reference: