Asked  7 Months ago    Answers:  5   Viewed   84 times

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];



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

Swift 4.2 & Swift 5:

    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

Tuesday, June 1, 2021
answered 7 Months ago

You can improve your code with these steps:

extension Notification.Name {
    static let dataDownloadCompleted = Notification.Name(
       rawValue: "dataDownloadCompleted")

And use it like this:

let notificationCenter = NotificationCenter.default
                               selector: #selector(YourClass.sayHello),
                               name: .dataDownloadCompleted,
                               object: nil)

But as was already pointed out, issue is solved by changing to #selector

Wednesday, August 11, 2021
answered 4 Months ago

@Sh_Khan is right:


You can get even further, as mentioned in the Apple Documentation:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

Monday, September 20, 2021
answered 3 Months ago

This worked for me

   let NC = NotificationCenter.default

   self.NC.addObserver(forName: .NEVPNStatusDidChange, object: nil, queue: nil, 
                       using: self.VPNDidChangeStatus)

   func VPNDidChangeStatus(_ notification: Notification) {

Saturday, September 25, 2021
Ahmed Haque
answered 2 Months ago

In Swift 3, generate() has been renamed to makeIterator(). Changing the name of your function should fix the problem. (Note that other names have also changed, like AnyGenerator → AnyIterator, but it looks like that one has already been taken care of in your code.)

This change was implemented as part of SE-0006: Apply API Guidelines to the Standard Library.

Tuesday, November 9, 2021
Pedro Dusso
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :