iphone device current orientation in ViewDidLoad

When the app first loads, UIDevice.current.orientation isn't valid. But UIApplication.shared.statusBarOrientation is. UIDevice.current.orientation is the better way to check orientation, in general, though. So, this method will handle all situations

var isLandscape: Bool {
    return UIDevice.current.orientation.isValidInterfaceOrientation 
        ? UIDevice.current.orientation.isLandscape 
        : UIApplication.shared.statusBarOrientation.isLandscape
}

Your code is absolutely correct and there is no problem.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

This statement only works in original devices.

However you want to check in simulator you can check as

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
    // portrait             
} else {
    // landscape
}

Update:

I have tested for you in both device and simulator. Initially it would show portrait only in viewDidLoad though you will keep device in landscape. First Controller will look into shouldAutoRotate method.

You should not depend on viewDidLoad for initial orientation. You should depend on shouldAutorotate method initially for exact orientation.

Tags:

Ios

Iphone