Search code examples
swiftselectornsnotificationcenterobserversnsdistributednotification

How to detect switch between macOS default & dark mode using Swift 3


I want to change my status bar app icon when the user switches from default to dark mode and vice versa (using Swift 3). Here’s what i have so far:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    DistributedNotificationCenter.default().addObserver(self, selector: #selector(darkModeChanged(sender:)), name: "AppleInterfaceThemeChangedNotification", object: nil)
}

...

func darkModeChanged(sender: NSNotification) {
    print("mode changed")
}

Unfortunately, it’s not working. What am I doing wrong?


Solution

  • I'm using this Swift 3 syntax successfully:

    DistributedNotificationCenter.default.addObserver(self, selector: #selector(interfaceModeChanged(sender:)), name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil)
    
    func interfaceModeChanged(sender: NSNotification) {
      ...
    }