Storing and retrieving data with HealthKit

All data that is stored in the HealthKit store is stored as an HKSample subclass, and is associated with a corresponding HKObjectType and an HKObject. Together, these objects describe what a user did, what value is associated with the sample, and when it occurred. The following code is a sample of adding a short walk of 100 meters to the HealthKit store:

let object = HKQuantity(unit: HKUnit.meter(), doubleValue: 100)
let objectType = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
let distance = HKQuantitySample(type: objectType!, quantity: object, start: Date(), end: Date())

healthKitStore.save(distance) { success, error in
  print(success)
  print(error)
}

To provide greater flexibility and unit conversion, HealthKit uses HKUnit objects to represent units like meters, inches, pounds, liters, and more. Because all HealthKit operations are asynchronous, the save(_:withCompletion:) method takes a completion callback that is called after the operation has completed.

To retrieve data from the HealthKit store, you use HKQuery objects. For instance, to retrieve a user's active energy burned for the past ten days, you would use a query that looks as follows:

let predicate = NSPredicate(format: "%K > %@", HKPredicateKeyPathStartDate, (Date() - 60 * 60 * 24 * 10) as NSDate)
let sortDescriptors = [NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)]
let objectType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!
let query = HKSampleQuery(sampleType: objectType, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: sortDescriptors]) { query, samples, error in
  print(samples)
  print(error)
  print(query)
}

healthKitStore.execute(query)

The preceding sample sets up an NSPredicate to filter the results that are returned by the query. HealthKit provides several helpers, including HKPredicateKeyPathStartDate, so you don't have to manually type the correct key paths that are used to filter and sort data.

The records that you receive from HealthKit contain metadata about the record itself. For instance, you can read the value that is associated with the record, the start and end dates, and even the source that added the record to the HealthKit store. All data that you retrieve from HealthKit is immutable. This means that you can't modify existing records that have already been saved to HealthKit.

The previous samples for storing and fetching data used metrics that are expressed as HKQuantitySample objects. This type of object is for data that is represented as a certain number. Walking distance, calories burned, or even weight are examples of this.

HealthKit also records data in the form of HKCategorySample. The value for a category sample is expressed as an enum value. Sleep tracking is an example of a metric that is tracked as a category sample. The user is either in bed, asleep, or awake. You can't add custom values to this type of sample.

Now that you are up to speed with gaining access to the HealthKit store and know how to read and write data, let's implement a small application that tracks a user's walks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset