Reputation: 199
I am working on an iPhone(Swift) app and I have a WebView which loads a Youtube video and I would like to allow landscape mode only when the video is full screen. My whole app is portrait and rotation is disabled when the video is not playing in full screen. I don't want the user to be able to rotate the app to landscape when the youtube video is not in full screen, only when the video is playing in full screen.
I tried the following code, but it doesn't work.
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}
Upvotes: 0
Views: 4109
Reputation: 73
I came across this problem recently and using Zell B.'s answer, here is a Swift 5 version that will detect an AVPlayer and update the orientation settings.
Just copy and paste the below code into your AppDelegate (no editing necessary):
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if let currentVC = getCurrentViewController(self.window?.rootViewController), currentVC is AVPlayerViewController {
return .allButUpsideDown
}
return .portrait
}
func getCurrentViewController(_ viewController: UIViewController?) -> UIViewController? {
if let tabBarController = viewController as? UITabBarController {
return getCurrentViewController(tabBarController.selectedViewController)
}
if let navigationController = viewController as? UINavigationController{
return getCurrentViewController(navigationController.visibleViewController)
}
if let viewController = viewController?.presentedViewController {
return getCurrentViewController(viewController)
}
return viewController
}
Upvotes: 0
Reputation: 10286
supportedInterfaceOrientations
was not such a reliable solution in my case as well. What I did was getting current view controller in app delegate application supportedInterfaceOrientationsForWindow
method and checked if that controller was a view controller that supported all orientations so its return value was calculated based on this condition
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
if let currentVC = getCurrentViewController(self.window?.rootViewController){
//VideoVC is the name of your class that should support landscape
if currentVC is VideoVC{
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}
func getCurrentViewController(viewController:UIViewController?)-> UIViewController?{
if let tabBarController = viewController as? UITabBarController{
return getCurrentViewController(tabBarController.selectedViewController)
}
if let navigationController = viewController as? UINavigationController{
return getCurrentViewController(navigationController.visibleViewController)
}
if let viewController = viewController?.presentedViewController {
return getCurrentViewController(viewController)
}else{
return viewController
}
}
Upvotes: 1