Accessing Pedometer Data in watchOS 2

One of the features that makes the Apple Watch a compelling fitness-tracking device is the fact that is has a built-in pedometer. This means it tracks your step count and distance independently from your phone.

(When recording your step count data to HealthKit, iOS performs some magic to combine duplicate step counts when holding your watch and phone at the same time).

You can directly access the pedometer data on the Apple Watch using the CoreMotion framework.

import CoreMotion

let pedometer = CMPedometer()  

There are two ways of retrieving data:

  1. Retrieve all data between a start and finish date
  2. Subscribe to updates so you're notified when there is new data available.

Data is returned from CMPedometer asynchronously using CMPedometerHandler. This is defined as follows:

public typealias CMPedometerHandler = (CMPedometerData?, NSError?) -> Void  

There are a number of values available in the CMPedometerData object, including:

let data: CMPedometer = ...

data.startDate // Beginning of data date range  
data.endDate // End of data date range

data.numberOfSteps // Number of steps taken  
data.distance // Distance travelled, in metres  

Retrieving All Data Between Two Dates

To retrieve all data between two dates, the following method is used:

public func queryPedometerDataFromDate(start: NSDate, toDate end: NSDate, withHandler handler: CMPedometerHandler)  

To query all data for the last hour, you could use the following code:

let endDate = NSDate()

let calendar = NSCalendar.currentCalendar()  
let startDate = calendar.dateByAddingUnit(.Hour, value: -1, toDate: NSDate(), options: [])

pedometer.queryPedometerDataFromDate(startDate, toDate: endDate) { (data: CMPedometerData?, error: NSError?) -> Void in

    if let data = data {
        let numSteps = data.numberOfSteps
        let distance = data.distance

        // Now do something with these values
    }
}

Subscribing to Pedometer Updates

Similarly, you can subscribe to updates so whenever new data is available, your code is notified.

This is achieved using the following CMPedometer method:

public func startPedometerUpdatesFromDate(start: NSDate, withHandler handler: CMPedometerHandler)  

To stop receiving updates, you use:

public func stopPedometerUpdates()  

To subscribe to all pedometer updates from now, you can use code similar to the following:

pedometer.startPedometerUpdatesFromDate(NSDate(), withHandler: { (data: CMPedometerData?, error: NSError?) -> Void in

    if let data = data {
        let numSteps = data.numberOfSteps
        let distance = data.distance

        // Now do something with these values
    }
}

And when you're done reading the data, use the following:

pedometer.stopPedometerUpdates()