Search code examples
iosswiftorientationfullscreenavplayer

iOS 8 - change orientation back to portrait when dismissing full screen AVPlayerViewController


my app is a portrait only app, but I have one view controller which is displaying a live stream, using an AVPlayerViewController.

To allow landscape for the full screen view of that player I wrote this method in the AppDelegate.swift:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
    var orientation =  UIInterfaceOrientationMask.Portrait

    if let presentedController = window?.rootViewController?.presentedViewController? {

        if presentedController.isKindOfClass( NSClassFromString("AVFullScreenViewController").self ) {
            orientation = .AllButUpsideDown
        } else if let navController = presentedController as? UINavigationController {
            if navController.topViewController.isKindOfClass( NSClassFromString("AVFullScreenViewController").self ) {
               orientation = .AllButUpsideDown
            }
        }
    }

    return  Int(orientation.rawValue)
}

This is how I call initialise my AVPlayer:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showLiveStream" {

        SVProgressHUD.show()
        var queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

        dispatch_async(queue, {
            let streamURL = NSURL(string: liveStreamURL)
            let playerItem = AVPlayerItem(URL: streamURL)
            let player = AVPlayer(playerItem: playerItem)

            dispatch_async(dispatch_get_main_queue(), {
                SVProgressHUD.dismiss()
                var playerViewController = segue.destinationViewController as AVPlayerViewController
                playerViewController.player = player
            })
        })
    }
}

The problem: when I open up the full screen view of the player, then change to landscape and then click "Done" to dismiss the full screen view, my app stays in landscape. But I want it to rotate to portrait again. How can I do that?


Solution

  • Rather than implementing application(_:supportedInterfaceOrientationsForWindow:) try implementing supportedInterfaceOrientations() on each view controller. So for example:

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue)
    }
    

    This will ensure that the view controller cannot be displayed in landscape, so when dismissing the video player, it will come straight back to a portrait window.

    Update Objective-C:

    - (NSUInteger)supportedInterfaceOrientations { 
        return UIInterfaceOrientationMaskPortrait; 
    }