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

A step by step iOS tutorial on getting the correct device orientation of an iPhone or iPad, on launch or after. Github repository included.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 02/10/2023 at 14:21
Last Updated on 02/10/2023 at 16:26
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.

SubscribeHow to create a SwiftLint enabled Swift XCode project

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.

Download Open Source ProjectSearch our blog for more Swift Tutorials

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe