1

I need to identify which way iOS device is tilting, left, right, forward, backward.

I am trying to identify this with below code but not working.

self.motionManager.isDeviceMotionAvailable {
    self.motionManager.deviceMotionUpdateInterval = 1
    self.motionManager.startDeviceMotionUpdates(to: OperationQueue()) { [weak self] (motion, error) -> Void in
        if let attitude = motion?.attitude {
            if attitude.pitch > 0{
                print("forward");
            }else if attitude.pitch <= 0{
                print("backward");
            }
            else if (attitude.roll <= -1){
                print("left");
            }else if(attitude.roll > 1){
                print("roght");
            }
            DispatchQueue.main.async{
                // Update UI
            }
        }
    }
    print("Device motion started")
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Sekhar Bhetalam
  • 4,501
  • 6
  • 33
  • 52
  • What does it do? Try to print pitch, roll and yaw to debug easily. – Louis Lac Apr 29 '20 at 17:36
  • 1
    Note that you used else-if blocks but a device can point at multiple directions at the same time. You should also verify tar angles are given in radians or degrees, or are normalised. – Louis Lac Apr 29 '20 at 17:38
  • @LouisLac, could you please help me on identifying angles are radians or degrees. I am very new to this. – Sekhar Bhetalam Apr 30 '20 at 08:18
  • 1
    Sure, just dig in Apple's documentation for CMMotionManager there is a ton of information. Especially focus on the type of the `attitude`type you are using: https://developer.apple.com/documentation/coremotion/cmattitude – Louis Lac Apr 30 '20 at 08:27
  • 1
    You should also check `referenceFrame` as it could be important for your application. – Louis Lac Apr 30 '20 at 08:28

0 Answers0