How to correctly get accelerometer data using Swift in iOS?

I am trying to write data from an iPhone accelerometer (my own iPhone 5s) and set a label on the screen for that data with String(format: "%.2f", data), where the data is the value for the particular axis I want to record. To do this, I set up CMMotionManager and started writing accelerometer data, and I have a timer that constantly updates the text in the shortcut. However, I get an error from Xcode: "Fatal error: nil unexpectedly found while deploying an optional value." Here is the relevant code:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //if accelerometer can be used, start it
    if (motionManager.accelerometerAvailable) {

        motionManager.accelerometerUpdateInterval = 0.1

        motionManager.startAccelerometerUpdates()
        let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
    }



}

func update () {
    if (motionManager.accelerometerActive) {

        accelX.text = String(format: "%.2f", motionManager.accelerometerData.acceleration.x)
    }

}

, accelX.text , , , , - . , , - , , , , .

+4
1

NSHipster , : http://nshipster.com/cmdevicemotion/

, :

if manager.accelerometerAvailable {
     manager.accelerometerUpdateInterval = 0.1
     manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
     [weak self] (data: CMAccelerometerData!, error: NSError!) in
          accelX.text = String(format: "%.2f", data.acceleration.x)
     }
}
+6

Source: https://habr.com/ru/post/1569906/


All Articles