---
title: "#42: HealthKit Basics 🏥"
url: https://littlebitesofcocoa.com/42-healthkit-basics
author: Jake Marsh
date: 2015-07-21
published: 2015-07-21
topics: ["HealthKit"]
description: "Let's use HealthKit to retrieve the user's current weight. HealthKit requires itemized authorization for each bit of data we want to read or write."
---

# #42: HealthKit Basics 🏥

By Jake Marsh, July 21, 2015. HTML: https://littlebitesofcocoa.com/42-healthkit-basics

Let's use **HealthKit** to retrieve the user's current weight. **HealthKit** requires itemized authorization for each bit of data we want to read or write. Here we ask to write nothing, and read weight only.

``` swift
import HealthKit

guard HKHealthStore.isHealthDataAvailable() else { return }

let store = HKHealthStore()

let weightQuantity = HKQuantityType.quantityTypeForIdentifier(
  HKQuantityTypeIdentifierBodyMass
)!

store.requestAuthorizationToShareTypes(
  nil,
  readTypes: [weightQuantity]
) { succeeded, error in
  guard succeeded && error == nil else { return; }

  // success!
}
```

Then the fun part: We execute a sample query, grabbing the latest weight result. Then we format the weight using `NSMassFormatter`.

``` swift
let sortDescriptor = NSSortDescriptor(
  key: HKSampleSortIdentifierEndDate,
  ascending: false
)

let query = HKSampleQuery(
  sampleType: weightQuantity, 
  predicate: nil, 
  limit: 1, 
  sortDescriptors: [sortDescriptor]
) { query, results, sample in
  guard let results = results where results.count > 0 else { return }

  let sample = results[0] as! HKQuantitySample
  let weightInPounds = sample.quantity.doubleValueForUnit(HKUnit.poundUnit())

  let suffix = NSMassFormatter().unitStringFromValue(
    weightInPounds,
    unit: .Pound
  )

  let formattedWeight = NSNumberFormatter.localizedStringFromNumber(
    NSNumber(double: weightInPounds),
    numberStyle: .NoStyle
  )

  print("User currently weighs: \(formattedWeight) \(suffix)")
}

store.executeQuery(query)
```
