iOS Swift - Detecting external display

Hi


I am trying to detect an external display using iOS Swift. The second display is connected with a Lightning Digital AV Adapter and HDMI. I have imported UIKIt. UIScreen.screens.count always == 1. It equals 1 even if I start the app with an external screen already being mirrored. How can I test for an external display so that I can initialize its view?

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 the second screen.


This link Is what helped:

http://tutorials.tinyappco.com/Swift/AdditionalScreen

Swift 5.5.1

I know this is old and for iOS, but it may help someone who is trying to figure this out and comes across this question.

I don't know if the same notification works in iOS, but there should be a similar way if not.

You can use the notification NSApplication.didChangeScreenParametersNotification

import Cocoa

class ViewController: NSViewController {

    var externalDisplayCount:Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        externalDisplayCount = NSScreen.screens.count
        setupNotificationCenter()
    }

    func setupNotificationCenter() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleDisplayConnection),
            name: NSApplication.didChangeScreenParametersNotification,
            object: nil)
    }

    @objc func handleDisplayConnection(notification: Notification) {
        if externalDisplayCount < NSScreen.screens.count {
            print("An external display was connected.")
            externalDisplayCount = NSScreen.screens.count
        } else if externalDisplayCount > NSScreen.screens.count {
            print("An external display was disconnected.")
            externalDisplayCount = NSScreen.screens.count
        } else {
            print("A display configuration change occurred.")
        }
    }
}

Notice that the final else is there and will be triggered whenever something changes with any of the connected displays configuration, such as toggling fullscreen mode on a display, or through system preferences.

iOS Swift - Detecting external display
 
 
Q