Search code examples
iosswiftaccelerometermotion

How use accelerometer in swift 3


I need help to use accelerometer with swift 3.

This is my code:

var motion = CMMotionManager()

@IBOutlet weak var statusAccel: UILabel!

override func viewDidAppear(_ animated: Bool) {
    motion.startAccelerometerUpdates(to: OperationQueue.current!){
        (data , error) in

        if let trueData = data {
            self.view.reloadInputViews()
            self.statusAccel.text = "\(trueData)"
        }
    }
}

It works but it just show me X Y and Z and i want to use Z.

Example : if Z = 2 do something


Solution

  • The data object that gets returned by startAccelerometerUpdates(...) is of type CMAccelerometerData which has a CMAcceleration property. From this you can get the z component.

    var motion = CMMotionManager()
    
    @IBOutlet weak var statusAccel: UILabel!
    
    override func viewDidAppear(_ animated: Bool) {
        motion.startAccelerometerUpdates(to: OperationQueue.current!){
            (data , error) in
    
            if let trueData = data {
                self.view.reloadInputViews()
                self.statusAccel.text = "\(trueData)"
    
                if trueData.acceleration.z == 2 {
                    // do things...
                }
            }
        }
    }