Search code examples
iosiphoneswiftcore-motion

Trying to rotate an image according to the angle of the device


I am trying to rotate an image based on the angle the device is at however when I implement my code nothing happens to the image. Here is my code:

import UIKit

import CoreMotion

 class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    let manager = CMMotionManager()
    let queue = OperationQueue()

    override func viewDidLoad() {
        super.viewDidLoad()
        manager.deviceMotionUpdateInterval = 0.01

        if manager.isDeviceMotionAvailable {

            manager.startDeviceMotionUpdates(to: queue) {
                [weak self] (data: CMDeviceMotion?, error: Error?) in
                    if let gravity = data?.gravity {
                        let rotation = atan2(gravity.x, gravity.y) - M_PI
                        self?.imageView.transform = CGAffineTransform(rotationAngle: CGFloat(rotation))

                    }
            }
        }
        manager.startDeviceMotionUpdates()
    }
}

The problem is the if let data = manager.deviceMotion never runs. I am not getting any errors and am wondering what the problem is. Any help is appreciated.


Solution

  • I fixed the problem by calling manager.startGyroUpdates() instead of manager.startDeviceMotionUpdates()