How to Detect the Orientation of the Device on iOS

Swift - How to detect orientation changes


let const = "Background" //image name
let const2 = "GreyBackground" // image name
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()

imageView.image = UIImage(named: const)
// Do any additional setup after loading the view.
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
imageView.image = UIImage(named: const2)
} else {
print("Portrait")
imageView.image = UIImage(named: const)
}
}

How to detect orientation change?

Here's how I got it working:

In AppDelegate.swift inside the didFinishLaunchingWithOptions function I put:

NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

and then inside the AppDelegate class I put the following function:

func rotated() {
if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
print("Landscape")
}

if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
print("Portrait")
}
}

Hope this helps anyone else!

Thanks!

Detecting iOS UIDevice orientation

Try doing the following when the application loads or when your view loads:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];

Then add the following method:

- (void) orientationChanged:(NSNotification *)note
{
UIDevice * device = note.object;
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
/* start special animation */
break;

case UIDeviceOrientationPortraitUpsideDown:
/* start special animation */
break;

default:
break;
};
}

The above will allow you to register for orientation changes of the device without enabling the autorotate of your view.



Note

In all cases in iOS, when you add an observor, also remove it at appropriate times (possibly, but not always, when the view appears/disappears). You can only have "pairs" of observe/unobserve code. If you do not do this the app will crash. Choosing where to observe/unobserve is beyond the scope of this QA. However you must have an "unobserve" to match the "observe" code above.

How to detect iOS device orientation from background?

There is a private method called -[UIApplication _getSpringBoardOrientation] which just calls another private method -[UIApplication activeInterfaceOrientation], which seems to give you the orientation of the current foreground app.

Get current iOS device orientation even if device's orientation locked

Declare motion manger with core motion

    var orientationLast = UIInterfaceOrientation(rawValue: 0)!
var motionManager: CMMotionManager?

Motion manager initialisation

and call this function in viewDidLoad

    func initializeMotionManager() {
motionManager = CMMotionManager()
motionManager?.accelerometerUpdateInterval = 0.2
motionManager?.gyroUpdateInterval = 0.2
motionManager?.startAccelerometerUpdates(to: (OperationQueue.current)!, withHandler: {
(accelerometerData, error) -> Void in
if error == nil {
self.outputAccelertionData((accelerometerData?.acceleration)!)
}
else {
print("\(error!)")
}
})
}

To analyis accelerometers meter data

 func outputAccelertionData(_ acceleration: CMAcceleration) {
var orientationNew: UIInterfaceOrientation
if acceleration.x >= 0.75 {
orientationNew = .landscapeLeft
print("landscapeLeft")
}
else if acceleration.x <= -0.75 {
orientationNew = .landscapeRight
print("landscapeRight")
}
else if acceleration.y <= -0.75 {
orientationNew = .portrait
print("portrait")

}
else if acceleration.y >= 0.75 {
orientationNew = .portraitUpsideDown
print("portraitUpsideDown")
}
else {
// Consider same as last time
return
}

if orientationNew == orientationLast {
return
}
orientationLast = orientationNew
}


Related Topics



Leave a reply



Submit