4

I am trying to detect an external display using iOS Swift. The second display is connected with a Lightning Digital AV Adapter. I have imported UIKIt. When I run the code below screens.count just gives me 1 even if I start the app with the second screen already attached and mirroring.

    override func viewDidLoad() {
    super.viewDidLoad()

    // Initialize an external screen if one is present
    let screens = UIScreen.screens
    print(screens.count)

    txtDisplay.text = String(screens.count)
    if screens.count > 1 {
        print("A second screen has been detected")
        //An external screen is available. Get the first screen available
        //self.initializeExternalScreen(externalScreen: screens[1] as UIScreen)
    }


}

I have loaded demo applications that claim to have this functionality but I just get the same result. Any ideas how I can detect a second display using Swift?

Thanks

jumpwire
  • 101
  • 1
  • 9

2 Answers2

4

I discovered that UIScreen.screens.count would only acknowledge the external second screen if I setup notifications. Once I setup observers in the NotificationCenter I finally got 'UIScreen.screens.count' to == 2. Then I was able to assign a view to UIScreen.screens1

This page has the details: http://tutorials.tinyappco.com/Swift/AdditionalScreen

jumpwire
  • 101
  • 1
  • 9
  • You will not be notified about mirrored screen – Максуд Даудов Nov 26 '17 at 20:10
  • That may be. The important thing for me was that it enabled me to include the external display in the UIScreens.screens count so that I could test for it and then display content on the external screen. Thanks for your help. – jumpwire Nov 26 '17 at 23:07
2

Mirrored screens are not represented in screens Array. Instead use main screens mirroredScreen property

UPDATE:

let mirrored = UIScreen.main.mirrored
self.initializeExternal(external: mirrored)
  • Thanks for the tip. Any idea how to test for a mirrored screen? I can only get nil. It might need to be initialized before not being nil. Documentation on mirrored screens is thin. The code below is as close as I could get. var mirrored: UIScreen! self.initializeExternalScreen(externalScreen: mirrored as UIScreen) – jumpwire Nov 25 '17 at 23:27
  • @jumpwire please, accept answer if it fits your question – Максуд Даудов Nov 26 '17 at 13:50