Search code examples
iosuideviceorientation

Check Device Orientation in Various State of the Application


How to find the Device Orientation in the following application states:

  1. First time launching application
  2. Application entering in to foreground

Solution

  • You Can detect orientation at first time launching application like this :

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
     {
    
     [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];
     }
    

    To detect the Orientations :

    -(void)deviceOrientationDidChange:(NSNotification *)notification
    {
             UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    
             //Ignoring specific orientations
             if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown || orientation == UIDeviceOrientationUnknown || currentOrientation == orientation)
             {
             //To check orientation ;
             }
    
             if ([[NSUserDefaults standardUserDefaults] boolForKey:@"deveiceorientation"])
             {
               // your orientation
             }
             else
            {
               [[NSUserDefaults standardUserDefaults] setObject:deviceOrientaion forKey:@"deveiceorientation"];
               [[NSUserDefaults standardUserDefaults] synchronize];
               // save your orientation
              }
    
    }
    

    On application enter foreground you can check the same using

    -(void)viewDidAppear:(BOOL)animated{
    
    }