iOS: AVPlayerViewController enable fullscreen rotation in portrait oriented application

ton252 picture ton252 · Feb 27, 2016 · Viewed 7.2k times · Source

I have a UIViewcontroller, which contains a AVPlayerViewController with AVPlayer. I want to enable rotation for AVPlayerViewController(when video is on fullscreen) and disable any rotation for UIViewController. How can I enable rotation only for videos(on fullscreen) in my app?

Answer

Сергей Билык picture Сергей Билык · Sep 9, 2016

Swift 2.2 In AppDelegate to allow rotation for player:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
        guard let vc = (window?.rootViewController?.presentedViewController) else {
            return .Portrait
        }

        if (vc.isKindOfClass(NSClassFromString("AVFullScreenViewController")!)) {
            return .AllButUpsideDown
        }

        return .Portrait
    }

Than create and use subclass of AVPlayerViewController for back to portrait mode when player exit full screen mode:

class YourVideoPlayer: AVPlayerViewController {

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if view.bounds == contentOverlayView?.bounds {
UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")
        }
    }