UIWebView 视频播放 默认全屏显示的问题

来源:互联网 发布:access数据库培训 编辑:程序博客网 时间:2024/05/18 00:40

自己做了一个视频播放的项目,需要在UIWebView中点击播放视频,播放后视频默认是竖屏,切换到横屏需要关闭锁屏,才能旋转全屏播放,体验非常不好。

在网上找了一天的解决方案,大多是  使用监听通知UIMoviePlayerControllerDidEnterFullscreenNotificatio MPMoviePlayerControllerDidEnterFullscreenNotification, 然后在去控制屏幕的旋转。

但是这方案iOS8以后就已经失效了,目前无法使用了。


要实现全屏播放,要实现两点

1.获取当前开启播放的事件和关闭视频播放的事件

2.开启视频时屏幕横屏,关闭时候恢复竖屏。


解决第一个要点,我找了两个方法,目前都可以成功

1、使用js 钩子获取当前的播放事件  

原文链接:http://dev.classmethod.jp/client-side/javascript/uiwebview-video-tag/ 

日文网站,不过看代码应该能懂哈,博主亲测可以实现视频监听。

2、使用系统通知

这个算取巧了,博主使用的这种方式,当点击视频加载出MPMoviewController的时候,相当于在Window上加了一层,会触发到下面两个通知。不过来电话之类的也会触发,不过我想不会影响这个问题。

      //播放器即将播放通知

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(videoStarted:)

                                                 name:UIWindowDidBecomeVisibleNotification

                                               object:self.view.window];

   // 播放器即将退出通知

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(videoFinished:)

                                                 name:UIWindowDidBecomeHiddenNotification

                                               object:self.view.window];



然后就是实现横屏的问题了

首先在AppDelegate 里面 添加一个全局变量并横竖屏代理方法,用来判断当前的view是否需要横屏,其他屏幕默认则是竖屏 (需要开启app的横竖屏控制)

// web视频播放时屏幕旋转播放

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

 

    if(_isFull){

        

        return UIInterfaceOrientationMaskAll;

    }

    return UIInterfaceOrientationMaskPortrait;

    

}

然后实现步骤1中的两个通知方法

- (void)videoStarted:(NSNotification *)notification {//开始播放

    

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    appDelegate.isFull =YES;

    

    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];

   //防止手动先把设备置为横屏

    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];

}


- (void)videoFinished:(NSNotification *)notification {//完成播放

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    

    appDelegate.isFull =NO;

    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];

    

    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];

    

}




0 0