Tuesday, January 7, 2014

Youtube iOS app like rotation for MPMoviePlayerViewController

Recently I had to implement youtube iOS app like rotation for MPMoviePlayerViewController. So the video can be correctly rotated. This is how I did it.
1 Listen for the UIDeviceOrientationDidChangeNotification notification.
2 Rotate the MPMoviePlayerViewController as needed.

Here is the code for rotation
- (void)detectOrientation {
    NSLog(@"handling orientation");
    [self setMoviePlayerViewOrientation:[[UIDevice currentDevice] orientation]];
}

- (void)setMoviePlayerViewOrientation:(UIDeviceOrientation)orientation {
    double height = [UIScreen mainScreen].bounds.size.height;
    //Rotate the view!
    CGFloat degree = 0;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    switch (orientation) {
        case UIDeviceOrientationPortrait:
        case UIDeviceOrientationPortraitUpsideDown:
            degree = 0;
            moviePlayerController.view.bounds = CGRectMake(0, 0, 320, height);
            break;
        case UIDeviceOrientationLandscapeLeft:
            degree = 90;
            moviePlayerController.view.bounds = CGRectMake(0, 0, height, 320);
            break;
        case UIDeviceOrientationLandscapeRight:
            degree = -90;
            moviePlayerController.view.bounds = CGRectMake(0, 0, height, 320);
            break;
        case UIDeviceOrientationFaceUp:
            if (previousOrientation == UIDeviceOrientationLandscapeRight) {
                degree = -90;
                moviePlayerController.view.bounds = CGRectMake(0, 0, height, 320);
            } else if(previousOrientation == UIDeviceOrientationLandscapeLeft) {
                degree = 90;
                moviePlayerController.view.bounds = CGRectMake(0, 0, height, 320);
            } else if (previousOrientation == UIDeviceOrientationPortraitUpsideDown || previousOrientation == UIDeviceOrientationPortrait) {
                degree = 0;
                moviePlayerController.view.bounds = CGRectMake(0, 0, 320, height);
            }
            break;
        default:
            break;
    }
    //lastOrientation = orientation;
    CGAffineTransform cgCTM = CGAffineTransformMakeRotation((degree) * M_PI / 180);
    moviePlayerController.view.transform = cgCTM;
    [UIView commitAnimations];
    [[UIApplication sharedApplication] setStatusBarOrientation:orientation];
    previousOrientation = orientation;
}

In order fire this method we need to add an observer to the UIDeviceOrientationDidChangeNotification. So inside the viewDidLoad method, the following code need to be added.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectOrientation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

Now you will have a rotation similar to the Youtube iOS app. Happy coding!!!

UPDATE
 As for iOS 8, this is not needed. New SDK handles this by itself!!!! :D :D