iOS 全局禁止横屏,但UIWebView 全屏播放视频,横屏,解决办法

iOS 全局禁止横屏,但UIWebView 全屏播放视频,横屏,解决办法git

UIWebview在播放网页视频的时候咱们须要进行是否全屏状态的监听。github

通常的需求是在播放视频时候须要横屏,退出全屏的时候不能横屏,可是UIWebview没有给出响应的方法,编程

本问题解决的Demo工程https://github.com/darren90/iOS_Demo/tree/master/02-UIWebviewapp

1:其余界面不支持横屏:

这个比较容易个人思路是
在APPDelegate.h文件中增长属性:是否支持横屏ide

/***  是否容许横屏的标记 */
@property (nonatomic,assign)BOOL allowRotation;

在APPDelegate.m文件中增长方法,控制所有不支持横屏atom

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

这样在其余界面想要横屏的时候,咱们只要控制allowRotation这个属性就能够控制其余界面进行横屏了。code

//需在上面#import "AppDelegate.h"
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
//不让横屏的时候 appDelegate.allowRotation = NO;便可

2:播放界面横屏:

2.1:播放界面横屏:网上的解决方案

网上有人给出两种方法:视频

第一:可是iOS8下失效,没有用
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(videoStarted:)name:@"UIMoviePlayerControllerDidEnterFullscreenNotification"object:nil];//server

第二:经过js,可是没有找到详细的,可解决的方案。blog

因此也就是没有找到成熟的方案,因此就本身分析了。

2.2:播放界面横屏:问题分析

方法总会有的,咱们要向监听UIWebView视频播放时候是否全屏,也就是咱们要能拿到播放视频的view或者是viewcontroller,可是因为UIWebView没有比较直观的方法,因此只能从其余地方下手了

经过Reveal咱们能够查看到view的一些层级关系,能够看出弹出播放的是AVPlayerView,在UIWindow上,

好了,问题到这已经很明晰了,咱们要么能拿到AVPlayerView,要呢拿到UIWindow才能控制播放界面,分析后发现AVPlayerView很差拿,可是UIWindow及很easy了。

2.3:播放界面横屏:问题解决

因此这里可使用UIWindow的通知,就能够解决

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];//进入全屏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏

在退出全屏时,增长逻辑让其强制编程竖屏,这样当全屏播放的时候,点击down("完成")时,就会自动变成竖屏了。

// 进入全屏
-(void)begainFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = NO;
    
    //强制归正:
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

实例Demo工程https://github.com/darren90/iOS_Demo/tree/master/02-UIWebview


欢迎您的访问...

微博:@IT_攻城师

github:@Darren90

做者:http://www.cnblogs.com/fengtengfei/


本文版权归本人和博客园全部,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文链接。