-1

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

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
MayBeMe
  • 7
  • 8
  • You want to use Z and get X,Y,Z. What is your problem? Do you need help with extracting the Z value from the triplet? On a side note, when you only analyse Z data, then it implies some assumptions on the calibration of the acclerometer and of the orientation before/during the movement. – Yunnosch Aug 28 '17 at 17:59

2 Answers2

1

You can access the acceleration on the Z-axis by calling CMAccelerometerData.acceleration.z. If you are unsure about how to access a certain property of a class, always check the documentation either in Xcode directly or on Apple's documentation website, you can save a lot of time with this approach.

motion.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: { data, error in
    guard error == nil else { return }
    guard let accelerometerData = data else { return }
    if accelerometerData.acceleration.z == 2.0 {
        //do something
    }
})
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

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...
            }
        }
    }
}
Paolo
  • 3,825
  • 4
  • 25
  • 41