Setting up a UIWindowScene for external display is always null

267 Views Asked by At

I'm trying to show a separate UIView on an External display. Before iOS 13 you could mirrored_window.screen = mirrored_screen

However, starting with iOS 13 that .screen setter has been deprecated. So I started looping through the screens to find the one to add my custom view too, but it always returns null.

What have I missed?

func setupMirroringForScreen2(_ externalScreen: UIScreen){
        
        // Find max resolution
        var max = CGSize(width:0,height:0)
        var maxScreenMode : UIScreenMode?
        
        for current in externalScreen.availableModes  {
            if maxScreenMode == nil || current.size.height > max.height || current.size.width > max.width{
                max = current.size
                maxScreenMode = current
            }
        }
        
        
        externalScreen.currentMode = maxScreenMode
        
        let mirrored_window = UIWindow(frame: externalScreen.bounds)
        mirrored_window.layer.contentsGravity = .resizeAspect
        
        // For iOS13 find matching UIWindowScene
        var matchingWindowScene: UIWindowScene? = nil
        
        let scenes = UIApplication.shared.connectedScenes
        
        print("total scenes \(scenes.count)")
        
        for aScene in scenes {
            if let windowScene = aScene as? UIWindowScene {
                if (windowScene.screen == externalScreen) {
                    print("found UIWindowScene that has matching screen")
                    matchingWindowScene = windowScene
                    break
                }
            }
        }
        
        // THIS IS WHERE IT FAILS
        guard let matchingWindowScene = matchingWindowScene else {
            print("[ERROR]  The  matchingWindowScene is null")
            return
        }
        
        mirrored_window.windowScene = matchingWindowScene
        mirrored_window.isHidden = false
        
        let mirrored_view = UIView(frame: externalScreen.bounds)
        let view_i_want_mirrored = UIView(frame: mirrored_view.bounds)
        
        mirrored_view.addSubview(view_i_want_mirrored)
        mirrored_window.addSubview(mirrored_view)
        
    }
0

There are 0 best solutions below