Search code examples
iosorientationlandscapeportrait

How to change device orientation when app returns to foreground from background in iOS?


I have changed the orientation from portrait to landscape when I go to second view controller successfully using the below code:

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

but when I go in background and return to foreground in second view controller, then I press button to go to the first view controller. I am changing the orientation from landscape to portrait using the below code but it's not working.

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if ([ConfigObjC currentPage] && [[ConfigObjC currentPage] isEqualToString:@"SubViewController"])
    {
        return UIInterfaceOrientationMaskLandscapeLeft;
    }
    else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

If I do not go to background,the above code works. How can I fix this problem?


Solution

  • Try this when you entered in forground mode-

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    
    if ( ([[UIDevice currentDevice] orientation] ==  UIDeviceOrientationPortrait)  )
    {
       // do something for Portrait mode
    }
    else if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) || ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft))
    {
       // do something for Landscape mode
    }