Rupinder Kaur
Rupinder Kaur

Reputation: 43

requestAuthorizationToShareTypes function completion block not getting called when asking permission for health kit from apple watch

let healthKitTypesToRead = Set(arrayLiteral:
        HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!,
        HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
        HKObjectType.workoutType()
    )

    // 2. Set the types you want to write to HK Store
    let healthKitTypesToWrite = Set(arrayLiteral:
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!,

        HKQuantityType.workoutType()
    )

    // 3. 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.apple.tutorials.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
        if( completion != nil )
        {
            completion(success:false, error:error)
        }
        return;
    }

    // 4.  Request HealthKit authorization

    healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
        if( completion != nil )
        {
            completion(success:success,error:error)
        }
    }

Upvotes: 2

Views: 659

Answers (1)

lehn0058
lehn0058

Reputation: 20257

The Apple Watch delegates the request to the user's iPhone, so you will need to add the following method to your iOS AppDelegate:

func applicationShouldRequestHealthAuthorization(application: UIApplication) {
    let healthStore = HKHealthStore()
    healthStore.handleAuthorizationForExtensionWithCompletion {(success, error) -> Void in
        // Add anything you need here after authorization
    }
}

Upvotes: 5

Related Questions