Write me some code to get users medication doses so I can build a medication adherence app
Asked on 06/15/2025
1 search
To build a medication adherence app using the HealthKit Medications API, you can follow these steps to fetch users' medication doses:
-
Authorization: First, ensure that your app has the necessary permissions to access medication data. When a user authorizes a medication, your app is automatically granted access to read that medication and its doses. You can initiate an authorization request by displaying a sheet for selecting data types requested for reading and sharing.
-
Fetching Medications: Use the
HKUserAnnotatedMedicationQueryDescriptor
to fetch the list of active and archived medications from HealthKit. This query does not require a predicate or limit if you want to fetch all medications. -
Fetching Dose Events: To fetch dose events for a specific medication, you can use the
HKMedicationDoseEvent
sample type. You can set up a query descriptor to fetch dose events by medication and log status. For example, you can fetch the latest dose event by writing a function that accepts anHKMedication
concept and returns a single optionalHKMedicationDoseEvent
. -
Handling Dose Events: Dose events are tied to a medication and capture the context and details of what was logged. You can use these events to create experiences based on how someone logged their medication, such as tracking skipped doses or doses taken.
-
Anchored Object Queries: To keep your app's data up to date, use anchored object queries. This approach is more efficient than setting up a paired observer query and a sample query. The SwiftAsync interface for anchored object queries allows you to execute the query on a background thread and process the results to update your app's state.
Here's a basic example of how you might set up a query to fetch medication doses:
import HealthKit
let healthStore = HKHealthStore()
func fetchMedicationDoses(for medication: HKMedication, completion: @escaping ([HKMedicationDoseEvent]?) -> Void) {
let doseType = HKObjectType.medicationDoseEventType()
let predicate = HKQuery.predicateForObjects(from: medication)
let query = HKSampleQuery(sampleType: doseType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, samples, error) in
guard let doseEvents = samples as? [HKMedicationDoseEvent], error == nil else {
completion(nil)
return
}
completion(doseEvents)
}
healthStore.execute(query)
}
For more detailed information and examples, you can refer to the Meet the HealthKit Medications API session from WWDC 2025.