CMPedometer is part of the Core Motion framework. One of the features it provides is the ability to retrieve the number of steps a user has taken during a given time period. Let’s take a look at how to do it:
import Timepiece
let pedometer = CMPedometer()
if CMPedometer.isStepCountingAvailable() {
// NSDate.beginningOfDay comes from the Timepiece library
pedometer.queryPedometerDataFromDate(NSDate.beginningOfDay, toDate: NSDate()) { data, error in
guard let data = data else { return }
print("The user has taken \(data.numberOfSteps) so far today, that's \(data.distance) meters!")
}
}
We first import the Timepiece library (covered in Bite #3) and create a pedometer object. Then we check if the device supports step counting, and then we ask for the pedometer data since the beginning of today. The call hands back a CMPedometerData
object which has properties representing the number of steps taken and the distance traveled.