Overview
Many apple mobile devices have motion APIs. There are many APIs and they all use the CMMotionManager
class. Usually you only have 1 instance of this class in a high level area like the AppDelegate. You can get more information about Core Motion here.
Content
Check availability first. deviceMotion checks for all others.
1
2
3
4
5
6
7
import CoreMotion
var motionManager = CMMotionManager()
var isCoreMotionAvailable = motionManager.accelerometerAvailable
isCoreMotionAvailable = motionManager.gyroAvailable
isCoreMotionAvailable = motionManager.magnetometerAvailable
isCoreMotionAvailable = motionManager.deviceMotionAvailable
Is the hardware active?
1
2
3
4
5
6
var motionManager = CMMotionManager()
var isHardwareActive = motionManager.accelerometerActive
isHardwareActive = motionManager.gyroActive
isHardwareActive = motionManager.magnetometerActive
isHardwareActive = motionManager.deviceMotionActive
The hardware is on, start looking for updates.
1
2
3
4
5
6
7
8
9
10
11
12
var motionManager = CMMotionManager()
motionManager.startAccelerometerUpdatesToQueue(queue: NSOperationQueue(), withHandler: {
(accelerometerData, error) in
// do stuff
})
/*
startGyroUpdatesToQueue()
startMagnetometerUpdatesToQueue()
startDeviceMotionUpdatesToQueue()
*/
Stop looking for updates.
1
2
3
4
5
6
var motionManager = CMMotionManager()
motionManager.stopAccelerometerUpdates()
motionManager.stopGyroUpdates()
motionManager.stopMagnetometerUpdates()
motionManager.stopDeviceMotionUpdates()