HealthKit unauthorized versus 0 records in set

158 views Asked by At

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
}
1

There are 1 answers

2
Allan On

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:

To help prevent possible leaks of sensitive health information, your app cannot determine whether a user has granted permission to read data. If you are not given permission, it simply appears as if there is no data of the requested type in the HealthKit store. If your app is given share permission but not read permission, you see only the data that your app has written to the store. Data from other sources remains hidden.