Воспроизведение видео YouTube в полноэкранном режиме и разрешение вращения только для видео для iOS7 и iOS8

Я пытаюсь воспроизвести видео YouTube на UIWebView, как показано ниже:

// Create the URL
_videoUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://www.youtube.com/watch?v=%@", _videoID]];

// Create the request with the URL
NSURLRequest *requestObj = [NSURLRequest requestWithURL:_videoUrl];

// Load the request into the Web View
[_webView loadRequest:requestObj];

Страница YouTube показывает, что когда я нажимаю на видео, оно начинает воспроизводиться, но не вращается.

Я провел неделю в поисках другого решения, внедрив «shouldAutorotate» и «supportedInterfaceOrientations», но безуспешно!

Последнее, что я пробовал, это добавить прослушиватель, если видео воспроизводится в полноэкранном режиме, в AppDelegate.m я добавил в «didFinishLaunchingWithOptions» код ниже:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerWillEnterFullscreenNotification:) name:MPMoviePlayerWillEnterFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerWillExitFullscreenNotification:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];

И реализовано:

- (void) moviePlayerWillEnterFullscreenNotification:(NSNotification*)notification {
self.allowRotation = YES; }

- (void) moviePlayerWillExitFullscreenNotification:(NSNotification*)notification {
self.allowRotation = NO; }

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.forceLandscapeRight) {
    return UIInterfaceOrientationMaskLandscapeRight;
}
if (self.allowRotation) {
    return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}

return UIInterfaceOrientationMaskPortrait; }

Проблема в том, что ни «moviePlayerWillEnterFullscreenNotification», ни «moviePlayerWillExitFullscreenNotification» не вызываются.

Помогите, пожалуйста!


person raed    schedule 23.05.2014    source источник


Ответы (3)


Нашел ответ:

я должен был использовать

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubeStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubeFinished:) name:@"UIMoviePlayerControllerWillExitFullscreenNotification" object:nil];

Вместо

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerWillEnterFullscreenNotification:) name:MPMoviePlayerWillEnterFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerWillExitFullscreenNotification:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];

И реализовать методы в моем ViewControler

-(BOOL) shouldAutorotate {
 return NO; }

-(NSUInteger)supportedInterfaceOrientations{
 return UIInterfaceOrientationMaskPortrait; }

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
 return UIInterfaceOrientationPortrait; }

Подробнее: Автоповорот iOS 6.0+ для встроенного видео YouTube

Надеюсь, это поможет :)

person raed    schedule 29.05.2014
comment
На самом деле я еще не пробовал это на iOS8 :(, извините! Но если вы найдете ответ, поделитесь им :) - person raed; 02.10.2014
comment
Вы нашли решение для iOS8? - person jerrygdm; 21.11.2014

Это мое решение проблемы в Swift. Он основан на ответах выше, но проще:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
  // if it's our window, portrait. Other windows are (probably) the fullscreen video player ;)
  if self.window == window {
    return .Portrait
  } else {
    return [.Portrait, .Landscape]
  }
}
person alcarv    schedule 19.10.2015

Я только что провел некоторые исследования и придумал решение для поддержки iOS7 и iOS8. Чтобы разрешить вращение приложения только при воспроизведении видео на YouTube, выполните следующие действия:

  1. AppDelegate.m

Импортируйте #import <MediaPlayer/MediaPlayer.h> и реализуйте функцию «supportedInterfaceOrientationsForWindow», как показано ниже:

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{

if ([[window.rootViewController presentedViewController]
     isKindOfClass:[MPMoviePlayerViewController class]] || [[window.rootViewController presentedViewController] isKindOfClass:NSClassFromString(@"MPInlineVideoFullscreenViewController")] || [[window.rootViewController presentedViewController] isKindOfClass:NSClassFromString(@"AVFullScreenViewController")]) {

    return UIInterfaceOrientationMaskAllButUpsideDown;
}else {

    if ([[window.rootViewController presentedViewController]
         isKindOfClass:[UINavigationController class]]) {

        // look for it inside UINavigationController
        UINavigationController *nc = (UINavigationController *)[window.rootViewController presentedViewController];

        // is at the top?
        if ([nc.topViewController isKindOfClass:[MPMoviePlayerViewController class]]) {
            return UIInterfaceOrientationMaskAllButUpsideDown;

            // or it's presented from the top?
        } else if ([[nc.topViewController presentedViewController]
                    isKindOfClass:[MPMoviePlayerViewController class]]) {
            return UIInterfaceOrientationMaskAllButUpsideDown;
        }
    }
}

return UIInterfaceOrientationMaskPortrait;
}
  1. ViewController.m

В вашем «ViewController.m» добавьте следующий код в «ViewDidLoad», этот код позволит вам создать прослушиватель, если видео воспроизводится в полноэкранном режиме:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // SetUp notifications when video gets played and stopped
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubeStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubeFinished:) name:@"UIMoviePlayerControllerWillExitFullscreenNotification" object:nil];

    // Init The Video WebView
    [self initVideoWebView];
}

Эта функция позволяет вам инициировать ваш WebView с URL-адресом YouTube:

- (void) initVideoWebView {

    // Create the URL
    _videoUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://www.youtube.com/watch?v=%@", _videoID]];

    // Create the request with the URL
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:_videoUrl];

    // Load the request into the Web View
    [_webView loadRequest:requestObj];
}

Последнее, что нужно сделать, это реализовать следующие функции в вашем ViewControler:

-(BOOL) shouldAutorotate {
 return NO; }

-(NSUInteger)supportedInterfaceOrientations{
 return UIInterfaceOrientationMaskPortrait; }

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
 return UIInterfaceOrientationPortrait; }

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait; }

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait; }

Если это помогло, повышайте рейтинг :)

person raed    schedule 22.11.2014
comment
В последнем блоке кода у вас есть два повторяющихся метода. - person Eidan Spiegel; 27.04.2015