Beyond counting steps

Description: Move beyond step counting in your app and give people a much richer understanding of their mobility. We’ll detail how you can take advantage of mobility metrics in iOS and watchOS to measure movement in more distinct and actionable ways. Learn about the latest HealthKit APIs for accessing mobility data, strategies for meaningful data aggregation, and how to interpret results for people using your app.

Apple is introducing a category of metrics to HealthKit that captures the complex and important elements of human movement, all via iPhone (8 and later) and Apple Watch (4 and later).

New Mobility metrics on iPhone

New Mobility metrics on Apple Watch

How to read HealthKit data

Request authorization:

/// Request authorization from the user 
self.healthStore = HKHealthStore() 

let typesToRead: Set = [ 
  HKObjectType.quantityType(forIdentifier:-walkingSpeed)!
]

self.healthStore.requestAuthorization(toShare: nil, read: typesToRead) { success, error in 
	if !success, let error = error { 
    print("Authorization failed: \(error.localizedDescription)") 
  }
}

Fetch the data of interest in the relevant time range:

// Select a time range 
let start = Calendar. current.date(byAdding: .day, value: -30, to: dateOfInjury)
let end = Calendar.current.date(byAdding: .day, value: 60, to: dateOfInjury)

let datePredicate = HKQuery.predicateForSamples(withStart: start, end: end, options: []) 

// Query walking speeds 
let walkSpeedType = HKSampleType.quantityType(forIdentifier: .walkingSpeed)!
let sortByStartDate = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true) 

let query = HKSampleQuery(
	sampleType: walkSpeedType, 
	predicate: datePredicate, 
	limit: HKObjectQueryNoLimit, 
  sortDescriptors: [sortByStartDate]) { _, samples, _ in
  visualizeWalkSpeeds(samples)
}
self.healthStore.execute(query) 

Missing anything? Corrections? Contributions are welcome 😃

Related

Written by

Federico Zanetello

Federico Zanetello

Software engineer with a strong passion for well-written code, thought-out composable architectures, automation, tests, and more.