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