healthDataAccessRequest(store:shareTypes:readTypes:trigger:completion:)
Requests permission to save and read the specified HealthKit data types.
Declaration
@preconcurrency nonisolated func healthDataAccessRequest(store: HKHealthStore, shareTypes: Set<HKSampleType>, readTypes: Set<HKObjectType>? = nil, trigger: some Equatable, completion: @escaping @Sendable (Result<Bool, any Error>) -> Void) -> some View
Parameters
- store:
The HealthKit store where you’re requesting authorization.
- shareTypes:
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.
- readTypes:
An optional 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.
- trigger:
A value used to trigger the request. This value must be a State variable. Any change to the variable triggers a request.
- completion:
A block that the system calls after the request is complete. The system passes the result parameter.
Discussion
HealthKit performs these requests asynchronously when you modify the trigger’s value. 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 authorization sheet when you modify the trigger’s value. The authorization sheet lists all the requested permissions. After the user finishes responding, HealthKit calls the 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 when you modify the trigger 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:
NSHealthShareUsageDescription customizes the message for reading data.
NSHealthUpdateUsageDescription customizes the message for writing data.
Set these keys in the Target Properties list on the app’s Info tab.
After users 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.