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.