1. 程式人生 > >iOS 讓只支援豎屏的App橫屏播放網頁視訊

iOS 讓只支援豎屏的App橫屏播放網頁視訊

應用本身只支援豎屏,當時又想讓應用中網頁視訊可以全屏播放,這種需求想必經常會有。

這裡提供一種方法,經過測試,能實現這種需求。

以下程式碼在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.0
f) { [[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。