Search code examples
iosiphonempmovieplayercontrolleruiinterfaceorientation

Set orientation of MPMoviePlayerController


My whole application is in portrait mode only and i am playing youtube video in my application. For you tube I am using UIWebview. When user click on play button in UIWebview it automatically launch the MPMoviePlayerController. So I did not declared any MPMoviePlayerController object. So I want MPMoviePlayerController support both portrait and landscape orientation. So please suggest.


Solution

  • If you use NavigationController, you could subclass it and do the following:

    #import "MainNavigationController.h"
    #import <MediaPlayer/MediaPlayer.h>
    
    @implementation MainNavigationController
    
    -(BOOL)shouldAutorotate
    {
        return YES;
    }
    
    -(NSUInteger)supportedInterfaceOrientations
    {
        if ([[[self.viewControllers lastObject] presentedViewController] isKindOfClass:[MPMoviePlayerViewController class]])
        {
            return UIInterfaceOrientationMaskAll;
        }
        else
        {
            return UIInterfaceOrientationMaskPortrait;
        }
    
    }
    @end
    

    Then you should set your app to support all orientations, and this code will allow orientation change only if it is playing your movie 'MPMoviePlayerController`.

    When calling your movie you should send a notification, so if user closes it in any orientation other than portraitit switches back to portrait.

    Something like this:

    - (IBAction)playButton:(id)sender {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlaybackDidFinish)
                                                     name:MPMoviePlayerPlaybackDidFinishNotification
                                                   object:self.player.moviePlayer];
    
        NSURL *url = [NSURL URLWithString:videoUrl];
    
        self.player = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
        self.player.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    
        [self presentMoviePlayerViewControllerAnimated:self.player]; 
    }
    
    -(void)moviePlaybackDidFinish
    {
        [[UIDevice currentDevice] setValue:
         [NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
                                    forKey:@"orientation"];
    }
    

    This should do it for you, let me know how it goes.