suji suji - 6 months ago 25
Swift Question

HealthKit is launching only once in Swift 2.0

I have integrated HealthKit framework into my application. The HealthKit is launching only once from the application.The below Code is in the singleton class created for HealthKit.

func requestAuthorization()
{

if (HKHealthStore .isHealthDataAvailable() == false)
{
return
}


let healthKitTypesToRead : Set = [
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierFitzpatrickSkinType)!,
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType)!
]

let healthKitTypesToWrite : Set = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyFatPercentage)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierLeanBodyMass)!
]


self.healthStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) {
(success, error) -> Void in
if !success{
print("error")
}
}
}


The method
requestAuthorization
is calling for button action from the viewcontroller,

@IBAction func healthIntegrationButton(sender: UIButton)
{
HealthKitHandler.shared.requestAuthorization()

}


Once I dismiss the healthkit app, then no action is happening for the button action. Again if I deleted the application from simulator & click the button healthkit app will launch.

Could anyone please help us what is wrong in the above code. Thanks in advance.

Answer

If the authorization has been already granted, the app won't show it again. It will just call the success handler directly.

Change your completion handler into:

self.healthStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) {
                (success, error) -> Void in
                if success {
                    print("success!")
                }
                else {
                    print("error")
                }
            }

and you should see the difference.

Comments