Swift – Rotate image using Gyroscope

Rotate a UIImageView using Gyroscope:

if motionManager.isDeviceMotionAvailable {
    motionManager.deviceMotionUpdateInterval = 0.01
    motionManager.startDeviceMotionUpdates(to: .main) { [weak self] (data, error) in
        guard let data = data, error == nil else {
            return
        }

        DispatchQueue.main.async {
            let rotation = atan2(data.gravity.x, data.gravity.y) - .pi
            self?.imageView.transform = CGAffineTransform(rotationAngle: CGFloat(rotation))
        }
    }
}
 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.