NEW! Master Swift design patterns with my latest book! >>

How to check whether an iPhone or iPad is upside down or face up

Paul Hudson       @twostraws

If your app needs to know the orientation of the user’s device – face up or face down – it takes only four steps to implement.

First, write a method that can be called when the device orientation changes:

@objc func orientationChanged() {

}

That needs to be marked @objc because it’s going to be called by the system whenever the accelerometer signals the orientation has changed. So, step two is to request those changes be sent to the new method:

NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: .UIDeviceOrientationDidChange, object: nil)

Third, ask the system to start checking for orientation changes:

UIDevice.current.beginGeneratingDeviceOrientationNotifications()

You shouldn’t leave that on all the time unless you need it; you should call beginGeneratingDeviceOrientationNotifications() when you’re done with the data.

Finally, you can read the orientation property of the current UIDevice to see what the orientation currently is. This property doesn’t work correctly unless you already asked UIKit to begin generating device orientation notifications, which is why the above steps were required:

if UIDevice.current.orientation == .faceDown {
    // it's face down
}

You probably want that inside orientationChanged() so that it reads values as they change.

Available from iOS 2.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Love Hacking with Swift?

Get all 40 projects in PDF and HTML: buy the Hacking with Swift book! It contains over 1300 pages of hands-on Swift coding, and will really help boost your iOS career

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>