A soft touch of Apple HealthKit :: HealthKit Tutorial

Screen Shot 2014-10-14 at 6.54.20 PM

HealthKit :: The HealthKit framework provides a structure that apps can use to share health and fitness data. HealthKit is designed to manage data from a wide range of sources, automatically merging the data from all the different sources based on users’ preferences. Apps can also access the raw data for each source and let the app perform its own merging.

Some Key feature related to HealthKit is following

  • To use Healthkit in your application , First you have to enable it . To  enable HeakthKit you have to perform following step .

         Project setting—>Capability pane —> make enable Healthkit

         This requires that you sign in to your Apple developer account, and   

          then acquires the  appropriate entitlements for your app.

  • The HealthKit data is not saved to iCloud or synced across multiple devices. The data is only kept locally on the user’s device. For security, the HealthKit store is encrypted when the device is not unlocked.
  • HealthKit can be used only in iPhone and iPod  , Not in iPad. Developer can check for HealthKit availability using  isHealthDataAvailable().it return a Boolean value that indicates whether HealthKit is available on this device.
  • HKHealthStore is used to managed all types of data in HealthKit.
         if let massNumber = numberString("50") {

      let weightType =   HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

            let weightValue = HKQuantity(unit: HKUnit(fromString: "kg"), doubleValue: massNumber)

            let metadata = [ HKMetadataKeyWasUserEntered : true ]

            let now = NSDate()

            let sample=HKQuantitySample(type: weightType, quantity: weightValue, startDate: now, endDate: now, metadata: metadata)
  • All access to the data is performed through a HKHealthStore object, and it is this that you request permissions from. access request of data from Store is done as following
private func requestAuthorisationForHealthStore() {

  let dataTypesToWrite = [



  let dataTypesToRead = [






  self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite),

    readTypes: NSSet(array: dataTypesToRead), completion: {

    (success, error) in

      if success {

        println("User completed authorisation request.")

      } else {

        println("The user cancelled the authorisation request. \(error)")



  • Samples are saved in store using HKHealthStore object . sample code for this is following


        func saveSampleToHealthStore(sample: HKObject) {

  println(“Saving weight”)

  self.healthStore?.saveObject(sample, withCompletion: {

    (success, error) in

    if success {

      println(“Weight saved successfully “)

    } else {

      println(“Error: \(error))




  • Data from Store can be retrieved from HKQuery . sample code to retrieve is following


          func perfromQueryForWeightSamples() {

  let endDate = NSDate()

  let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth,

    value: –2, toDate: endDate, options: nil)

  let weightSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

  let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,

    endDate: endDate, options: .None)

  let query = HKSampleQuery(sampleType: weightSampleType, predicate: predicate,

    limit: 0, sortDescriptors: nil, resultsHandler: {

    (query, results, error) in

      if !results {

        println(“There was an error running the query: \(error))


      var data=results as [HKQuantitySample]




HealthKit Support 50 type of exercise including

     • Archery

  • Yoga
  • Swimming
  • StairClimbing
  • SnowSports
  • SkatingSports
  • Hocket
  • Fishing
  • Dance
  • CrossTraining

Type of values that can be stored in store is following

  •          1. Body Mass
  •          2. Height
  •          3.Step Count
  •          4.Blood glucose
  •          5.Blood alcohol content
  •          6.Dietary energy consumed
  •          7.Body Temperature
  •          8.Inhaler usage

         these are known as HKTypeIdentifiers.

For detail check on https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Framework/index.html#//apple_ref/doc/uid/TP40014707


One thought on “A soft touch of Apple HealthKit :: HealthKit Tutorial

Add yours

  1. It was difficult to find your blog in google.
    You should create some high PR contextual backlinks in order
    to rank your blog. I know – writing articles is very time consuming, but contextual backlinks
    are the best type of backlinks. I know one cool tool that will help
    you to create unique, readable articles in minute, just
    type in google – rewriter creates an unique article in a minute


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: