Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate orientation changes in iOS for testing purposes

I would like to test my app's ability to handle orientation changes (portrait/landscape). I'm currently using KIF and as far as I know, it cannot do this. Is there a way to simulate the rotation events programmatically for the iOS simulator?

I don't care if it is some undocumented private API or hack because this will only run during testing and will not be part of production builds.

like image 364
Tomas Andrle Avatar asked Jun 18 '12 09:06

Tomas Andrle


2 Answers

Here is a step to achieve this:

+ (KIFTestStep*) stepToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation {

    NSString* orientation = UIInterfaceOrientationIsLandscape(toInterfaceOrientation) ? @"Landscape" : @"Portrait";
        return [KIFTestStep stepWithDescription: [NSString stringWithFormat: @"Rotate to orientation %@", orientation]
                             executionBlock: ^KIFTestStepResult(KIFTestStep *step, NSError *__autoreleasing *error) {
                                 if( [UIApplication sharedApplication].statusBarOrientation != toInterfaceOrientation ) {
                                     UIDevice* device = [UIDevice currentDevice];
                                     SEL message = NSSelectorFromString(@"setOrientation:");

                                     if( [device respondsToSelector: message] ) {
                                         NSMethodSignature* signature = [UIDevice instanceMethodSignatureForSelector: message];
                                         NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];
                                         [invocation setTarget: device];
                                         [invocation setSelector: message];
                                         [invocation setArgument: &toInterfaceOrientation atIndex: 2];
                                         [invocation invoke];
                                     }
                                 }

                                 return KIFTestStepResultSuccess;
                             }];
}

Note: Keep your device flat on a table or the accelerometer updates will rotate the view back.

like image 158
Paul de Lange Avatar answered Nov 15 '22 19:11

Paul de Lange


To simulate orientation change in UI Automation you can use the setDeviceOrientation method for UIATarget. Example:

UIATarget.localTarget().setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);

Method needs one parameter 'deviceOrientation' constant. More info here

This 100% works on the real iOS device. I'm not sure about simulator.

like image 4
Sh_Andrew Avatar answered Nov 15 '22 19:11

Sh_Andrew