How to get the device orientation of an iPhone or iPad in Swift
A step by step guide on getting the correct device orientation of an iPhone or iPad, on launch or after. Github repository included.
The following tutorial has been implemented into our Open Source Swift project's main branch and demonstrates how to get the UIDeviceOrientation for an iPhone or iPad.
The code considers that the UIDevice.current.orientation returns as unknown on launch and identifies the correct resolution for both iOS15 and below, using the UIApplication window interface orientation.
Step One: Add the Utility
If you don't already have a Utils folder in your root, create it.
Within it create a folder called Orientation.
Within the Orientation folder, create a file called getDeviceOrientation.swift and paste in the code below.
Step Two: Call the function
Call the function in the location where you wish to get the device orientation.
We called it in the viewDidLoad function of the ViewController.swift file to demonstrate it's success.
Step Three: Verify
Run the XCode project on an iPhone or iPad and witness how it correctly interprets the orientation, on launch of thereafter.