Chengyu SHEN

Graduate Student in USC

Swift Core Motion

Oct 26, 2017 / Written by Chengyu

This article shared my experience in using the CMMotionManager() in Swift.

1. What is Core Motion? What can we do with this package?

If the developer wants to access to the motion- and environment-related data from the embedded hardware from the iPhone, including the accelerometers, gyroscopes, pedometers, magnetometers and barometers, the core motion library provides corresponding functions. One prevalent example is a game might use accelerometer and gyroscope data.
Here is my understanding of accelerometers and gyroscopes : Even though both value changes as the user changes the device position. Accelerometers is the absolute position for the device but the gyroscpes is the relative position.

  coordinate in CoreMotion data  




2. How to use Core Motion properly

Firstly, we need to import this library:
import CoreMotion
Then we need to initialize a CMMotionManager:
var motionManager = CMMotionManager()
The following steps is going to talk about how to keep track of the accelerator/gyroscopes values:

override func viewDidAppear(_ animated: Bool) {
    //in case of generating acceleraometer data too repaidly.
    motionManager.accelerometerUpdateInterval = 0.3
    motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, err) in
        if let myData = data {
            print(myData.accleration.x)
            print(myData.accleration.y)
            print(myData.accleration.z)
        }
    }
}

For the above codes, you can use the function motionManager.startGyroUpdates() to keep track of gyroscopes value as well.
A new 3-dimension accelerometer data will be generated in every 0.3 seconds so you can call your own function inside this function.
I used one vertical slider whose cursor changes as the y value changes, therefore, I called the cursor change function whenever the value of myData changes.