Figure out iOS Device Orientation Manually with Swift

I had the problem that I coded an app that records video in landscape. Although only landscape orientation is allowed in the app, users would frequently hold the device in portrait mode and produce shitty videos. Therefore, I decided to show a note to the user demanding to hold the device horizontally when holding it upright. To achieve this, it was not possible using an out of the box means by iOS, as those automatic features require the app to work in landscape as well as in portrait mode (which, as stated above, my app didn’t).

To solve this problem, I employed CoreMotion to detect the device rotation manually using the accelerometer. You can check out my solution on Github. Basically, the following approach worked:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
motionManager.startAccelerometerUpdates()
 
if motionManager.isAccelerometerAvailable {
    motionManager.accelerometerUpdateInterval = 0.1
    motionManager.startAccelerometerUpdates(to: .main) {
        (data: CMAccelerometerData?, error: Error?) in
        if let acceleration = data?.acceleration {
            let rotation = atan2(acceleration.x, acceleration.y) - .pi
            if rotation <= -1.75 * .pi  || rotation > -0.25 * .pi {
                self.orientationLabel.text = "Portrait up"
            } else if rotation <= -0.25 * .pi  && rotation > -0.75 * .pi {
                self.orientationLabel.text = "Landscape right"
            } else if rotation <= -0.75 * .pi  && rotation > -1.25 * .pi {
                self.orientationLabel.text = "Portrait down"
            } else if rotation <= -1.25 * .pi  && rotation > -1.75 * .pi {
                self.orientationLabel.text = "Landscape left"
            }
        }
    }
}