Contents

requestAuthorization(toShare:read:completion:)

Requests permission to save and read the specified data types.

Declaration

func requestAuthorization(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping  @Sendable (Bool, (any Error)?) -> Void)

Parameters

  • typesToShare:

    A set containing the data types you want to share. This set can contain any concrete subclass of the Hksampletype class (any of the Hkquantitytype, Hkcategorytype, Hkworkouttype, or Hkcorrelationtype classes ). If the user grants permission, your app can create and save these data types to the HealthKit store.

  • typesToRead:

    A set containing the data types you want to read. This set can contain any concrete subclass of the Hkobjecttype class (any of the Hkcharacteristictype , Hkquantitytype, Hkcategorytype, Hkworkouttype, or Hkcorrelationtype classes). If the user grants permission, your app can read these data types from the HealthKit store.

  • completion:

    A block called after the user finishes responding to the request. The system calls this block with the following parameters:

    success

    A Boolean value that indicates whether the request succeeded. This value doesn’t indicate whether the user actually granted permission. The parameter is False if an error occurred while processing the request; otherwise, it’s True.

    error

    An error object. If an error occurred, this object contains information about the error; otherwise, it’s set to nil.

Discussion

HealthKit performs these requests asynchronously. If you call this method with a new data type (a type of data that the user hasn’t previously granted or denied permission for in this app), the system automatically displays the permission form, listing all the requested permissions. After the user has finished responding, this method calls its completion block on a background queue. If the user has already chosen to grant or prohibit access to all of the types specified, HealthKit calls the completion without prompting the user.

Each data type has two separate permissions, one to read it and one to share it. You can make a single request, and include all the data types your app needs.

Customize the messages displayed on the permissions sheet by setting the following keys:

For projects created using Xcode 13 or later, set these keys in the Target Properties list on the app’s Info tab. For projects created with Xcode 12 or earlier, set these keys in the apps Info.plist file. For more information, see Information Property List.

After users have set the permissions for your app, they can always change them using either the Settings or the Health app. Your app appears in the Health app’s Sources tab, even if the user didn’t allow permission to read or share data.

See Also

Accessing HealthKit