How to get the device orientation of an iPhone or iPad in Swift

Oscar de la Hera Gomez
Two flowers that represents Swift and XCode next to each other. Beneath them sits the text "Device Orientation."

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

A screenshot of Xcode showing the getDeviceOrientation function detailed below.

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

A screenshot of XCode showing how we called the getDeviceOrientation 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

A screenshot of Xcode with a highlight on the console, demonstrating that it first sees the device orientation as unknown before determining and returning the correct orientation.

Run the XCode project on an iPhone or iPad and witness how it correctly interprets the orientation, on launch of thereafter.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details