Apple Healthkit framewor overview

Source: http://www.iostechinfo.com/2015/10/apples-healthkit-framework-overview.html#

Apple’s HealthKit is a brand new framework that centralizes the data storage of personal health data information. Learn more from the framework.

  • Request authorization permission to access HealthKit data.
  • Read information and format it to show it in the screen.
  • Write data back to HealthKit.
  • Get the data from Health app.
  • How to save the user entered data.
  • How to Execute query.
  • Reads user characteristics.
  • Reads and saves quantity samples.
  • Reads and saves workout.
  • Interpret health data to make your apps more engaging and personal health info for your users.

Going to build a simple app that’ll request authorization to use HealthKit, and then read and write HealthKit data.

There are only five easy steps to integrate HealthKit into your app. The five steps are:

  1. Enable HealthKit in Xcode (select project Targets -> Capabilities)
  2. Check availability.
  3. Request authorization.
  4. Read/Write some data.
  5. Prepare for publishing.

Next, we go through each step and explain it in a little bit more detail.

1. Enable HealthKit:

 Click your project target settings in XCode and select the capabilities page. Enable HealthKit and XCode will do the rest for you (Ex. adding the HealthKit framework, etc.).

2. Check availability:

As a staring point keep in mind, that you should check the availability of HealthKit in any location you wish to use the API. Since the Health app is (currently) only available on iPhones (and not on iPads or iPods) this is a inevitable task. However, the code is quite easy:

if(NSClassFromString(@”HKHealthStore) && [HKHealthStore isHealthDataAvailable])
{
// Add your HealthKit code here
}

HealthKit is available on iOS 8.0 and later.

3.Request authorization:

HealthKit stores user sensitive data and Apple keeps an eye on users privacy, your app needs to request access to each data type separately. So you have to decide which data types you want toread  or read/write  (Apple calls the second mode share ).
func authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!)
{
  // 1. Set the types you want to read from HK Store
  let healthKitTypesToRead = Set(arrayLiteral:[
    HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth),
    HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType),
    HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight),
    HKObjectType.workoutType()
    ])
 
  // 2. Set the types you want to write to HK Store
  let healthKitTypesToWrite = Set(arrayLiteral:[
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning),
    HKQuantityType.workoutType()
    ])
 
  // 3. If the store is not available (for instance, iPad) return an error and don't go on.
  if !HKHealthStore.isHealthDataAvailable()
  {
    let error = NSError(domain: "com.raywenderlich.tutorials.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
    if( completion != nil )
    {
      completion(success:false, error:error)
    }
    return;
  }
 
  // 4.  Request HealthKit authorization
  healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
 
    if( completion != nil )
    {
      completion(success:success,error:error)
    }
  }
}

The above code will present an authorization screen in your app users which will look like the following screen :

4. Read/Write some data:

Reading and writing data from and to the health store is really straight forward. TheHKHealthStore class provides some convenient methods for reading basic characteristics. If you want to query some more complex data you have to use the corresponding subclasses of HKQuery. Below you will find three examples explaining some common use cases.

1. Query the biological sex of the user:

func readProfile() -> ( age:Int?,  biologicalsex:HKBiologicalSexObject?, bloodtype:HKBloodTypeObject?)
{
  var error:NSError?
  var age:Int?
 
  // 1. Request birthday and calculate age
  if let birthDay = healthKitStore.dateOfBirthWithError(&error)
  {
    let today = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let differenceComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: birthDay, toDate: today, options: NSCalendarOptions(0) )
    age = differenceComponents.year
  }
  if error != nil {
    println("Error reading Birthday: \(error)")
  }
 
  // 2. Read biological sex
  var biologicalSex:HKBiologicalSexObject? = healthKitStore.biologicalSexWithError(&error);
  if error != nil {
    println("Error reading Biological Sex: \(error)")
  }
  // 3. Read blood type
  var bloodType:HKBloodTypeObject? = healthKitStore.bloodTypeWithError(&error);
  if error != nil {
    println("Error reading Blood Type: \(error)")
  }
 
  // 4. Return the information read in a tuple
  return (age, biologicalSex, bloodType)
}
Advertisements

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