NEVERCODE Develop apps 20% faster with the leading CI/CD partner for iOS, Android, Cordova, Ionic, React Native & Flutter projects Try It

Active Filters: HealthKit

Topics

#42: HealthKit Basics 🏥

Topics

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.

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.

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)