iOS 9 Swift Programming Cookbook (2015)
Chapter 10. Core Motion
This year, Apple finally brought some long awaited features into the Core Motion framework. It’s especially exciting that the same capabilities, or some version of them, is also available on the Apple Watch. This is great news for us developers because we can program for the Watch in a more native way, rather than reading this data from the user’s iPhone and sending it to the watch with Bluetooth.
There are a couple key terms I’ll be using throughout this chapter that you need to know about:
Cadence
I use a cadence sensor on my bicycle. It helps me find figure out how many times I spin my pedals, which can be crucial knowledge. Think about riding downhill on a bicycle, at a 45 degree angle, for 20 minutes, out of a total 40-minute bike ride. Your total calories burned and effort will be miscalculated because you might not even have pedaled when going downhill. The Watch actually includes a cadence sensor for running.
Pace
This is a ratio, dividing the time you have moved by the distance. If you’re counting in meters, for instance, your pace might be 0.5 seconds per meter, meaning that you travelled 1 meter in half a second..
iOS devices can provide pace and cadence information when its available from the pedometer. Some pedometers might not have this information available. You can call the isPaceAvailable() class function of CMPedometer to find out whether pace information is available. Similarly, the isCadenceAvailable() class method of CMPedometer can tell you whether cadence information is available.
NOTE
Import the CoreMotion framework into your project before attempting to run the code we write in this chapter.
10.1 Querying Pace and Cadence Information
Problem
You want to get cadence and pace information from the pedometer on an iOS device.
Solution
Follow these steps:
1. Find out whether cadence and pace are available.
2. Call the startPedometerUpdatesFromDate(_:withHandler:) function of CMPedometer.
3. In your handler block, read the currentPace and currentCadence properties of the incoming optional CMPedometerData object.
Discussion
Let’s check an example out:
guard CMPedometer.isCadenceAvailable() &&
CMPedometer.isPaceAvailable() else{
print("Pace and cadence data are not available")
return
}
let oneWeekAgo = NSDate(timeIntervalSinceNow: -(7 * 24 * 60 * 60))
pedometer.startPedometerUpdatesFromDate(oneWeekAgo) {data, error in
guard let pData = data where error == nil else{
return
}
if let pace = pData.currentPace{
print("Pace = \(pace)")
}
if let cadence = pData.currentCadence{
print("Cadence = \(cadence)")
}
}
NOTE
When you finish querying pedometer data, always remember to call the stopPedometerUpdates() function on your instance of CMPedometer.
See Also