How to detect fullscreen mode using AVPlayerViewController in Swift?

前端 未结 5 572
花落未央
花落未央 2020-12-10 18:12

I am trying to detect when the AVPlayerViewController is in full-screen mode, but I\'m having a difficult time achieving this. I\'d like to know when the user s

5条回答
  •  一生所求
    2020-12-10 19:04

    This is a slightly optimized Swift 4.2 version of @Pangu's answer. It only detects the change, otherwise the observer is called also when interacting with the video like fast forwarding. I also replaced the "videoBounds" with the AVPlayerViewController.videoBounds keypath to avoid the string and use the window bounds to determine if it's fullscreen or not.

    avPlayerViewController.addObserver(self, forKeyPath: #keyPath(AVPlayerViewController.videoBounds), options: [.old, .new], context: nil)
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(AVPlayerViewController.videoBounds) {
            // detect only changes
            if let oldValue = change?[.oldKey] as? CGRect, oldValue != CGRect.zero, let newValue = change?[.newKey] as? CGRect {
                // no need to track the initial bounds change, and only changes
                if !oldValue.equalTo(CGRect.zero), !oldValue.equalTo(newValue) {
                    if newValue.size.height < UIScreen.main.bounds.height {
                       print("normal screen")
                    } else {
                       print("fullscreen")
                    }
                }
            }
        }
    }
    

提交回复
热议问题