This is a basic guide to HealthKit, covering how an app can insert data to Health app via the framework.
I added this feature, adding of constipation data, for the sake of app review.
Request for access
There are many data types available. Here, we are using .constipation
which is a HKObjectType.categoryType
.
guard let constipationType = HKObjectType.categoryType(forIdentifier: .constipation) else {
// Data type not available
return
}
let healthKitTypesToWrite: Set<HKSampleType> = [constipationType]
do {
try await HKHealthStore().requestAuthorization(toShare: healthKitTypesToWrite, read: [])
} catch {
errorMessage = "Please go to Settings > Health > Enable data access for the app"
}
One thing to note: If user did not grant access, calling this block of code again will not end up in the catch block. If you need to know, you can call HKHealthStore().authorizationStatus
, but that only works for write data.
To help prevent possible leaks of sensitive health information, your app cannot determine whether or not a user has granted permission to read data.
Info.plist keys
Add the key NSHealthUpdateUsageDescription
with an explanation why you need to add data to Health app.
Add the key NSHealthShareUsageDescription
with an explanation why you need to read data from Health app.
You MUST have both keys, even if you only need to insert data.
Insert data & save
Configure a sample and save to HealthKit. For constipation, a sample includes severity, start date and end date.
guard let constipation = HKSampleType.categoryType(forIdentifier: .constipation) else { return }
let serverity = HKCategoryValueSeverity.unspecified.rawValue
let sample = HKCategorySample(type: constipation, value: serverity, start: date1, end: date2)
do {
try await HKHealthStore().save(sample)
} catch {
errorMessage = error.localizedDescription
}