分享

【原】iOS 让只支持竖屏的App横屏播放网页视频

 叹落花 2016-05-11

应用本身只支持竖屏,当时又想让应用中网页视频可以全屏播放,这种需求想必经常会有。

这里提供一种方法,经过测试,能实现这种需求。

以下代码在Xcode7.1,iOS6~iOS9 测试通过。

首先在xxxxAppDelegate中增加一个属性:

@property (nonatomic, assign) BOOL allowRotation; // 标记是否可以旋转

.m文件中实现方法:

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)nowWindow {
    
    if (_allowRotation) {
        return UIInterfaceOrientationMaskAll;
    }
    else
    {
        return UIInterfaceOrientationMaskPortrait;
    }
}

Webview进入视频播放页面时候,系统会发出几个通知:

UIMoviePlayerControllerDidEnterFullscreenNotification // 进入全屏播放

UIMoviePlayerControllerWillExitFullscreenNotification // 将退出全屏播放

UIMoviePlayerControllerDidExitFullscreenNotification // 已退出全屏播放

因此,可以在包含Webview的Controller的viewDidLoad方法中添加两个通知监听,分别是:

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0f || [[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];// 播放器即将播放通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoFinished:) name:@"UIMoviePlayerControllerWillExitFullscreenNotification" object:nil];// 播放器即将退出通知
    }
    else
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoStarted:) name:UIWindowDidBecomeVisibleNotification object:nil];//进入全屏
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏
    }
}

#pragma - mark  视频进入全屏
-(void)videoStarted:(NSNotification *)notification
{
        xxxxAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
        appDelegate.allowRotation = YES;
}

#pragma - mark 视频将退出
-(void)videoWillFinished:(NSNotification *)notification
{
    xxxxAppDelegate *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];
    }
}

Over。

参考资料

  1. http://www./sj/ios8/90517.htm

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多