Search code examples
swiftnotificationswindowwebkitdetection

How to rewrite code for detect when AVPlayer is closed inside WKWebKit


I am need detect when AVPlayer was closed. When I am open website with with video content inside webkit and press on player AVPlayer will be opened and I am can detect this using code below:

override func viewDidLoad() {
        super.viewDidLoad()
        webkit.load(request)

 NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeVisibleNotification(notif:)), name: NSNotification.Name("UIWindowDidBecomeVisibleNotification"), object: nil)

}

@objc func windowDidBecomeVisibleNotification(notif: Notification) {
        
        
            if let isWindow = notif.object as? UIWindow {
                if (isWindow !== self.view.window) {
                    print("New window did open, check what is the currect URL")
                }
            }
         }

But I can't understand how rewrite this code if I am wan't opposite action when user close this player.

I am was try rewrite this code but my attempts is fails.


Solution

  • Need create two notificationcented observer for detect maximize and minimize avplayer

     override func viewDidLoad() {
            super.viewDidLoad()
    
    // listen for videos playing in fullscreen
            NotificationCenter.default.addObserver(self, selector: #selector(onDidEnterFullscreen(_:)), name: UIWindow.didBecomeVisibleNotification, object: view.window)
    
            // listen for videos stopping to play in fullscreen
        NotificationCenter.default.addObserver(self, selector: #selector(onDidLeaveFullscreen(_:)), name: UIWindow.didBecomeHiddenNotification, object: view.window)
    }
    
    @objc func onDidEnterFullscreen(_ notification: Notification) {
        print("Enter Fullscreen")
    }
    
    @objc func onDidLeaveFullscreen(_ notification: Notification) {
        print("Leave Fullscreen")
    }