NSNotificationCenter addObserver in Swift

ios, nsnotificationcenter, swift

Solution

It's the same as the Objective-C API, but uses Swift's syntax.

Swift 4.2 & Swift 5:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.batteryLevelChanged),
    name: UIDevice.batteryLevelDidChangeNotification,
    object: nil)

If your observer does not inherit from an Objective-C object, you must prefix your method with `@objc` in order to use it as a selector.

@objc private func batteryLevelChanged(notification: NSNotification){     
    //do stuff using the userInfo property of the notification object
}

See NSNotificationCenter Class Reference, Interacting with Objective-C APIs

Problem

How do you add an observer in Swift to the default notification center? I'm trying to port this line of code that sends a notification when the battery level changes. ``` [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil]; ```

Original source

Related problems