Search code examples
iosobjective-cswiftswift3

Objective-C observer - how to use in Swift


I'm adding new features with Swift to Objective-C app.

I have this observer in Objective-C (registration.m):

[[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(confirmSms) name:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil];

and in confirm.m:

[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil];

How to observe this in Swift? I've tried

NotificationCenter.default.removeObserver(self,
                                                  name: NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS,
                                                  object:nil);

NotificationCenter.default.addObserver(self,
                                              selector:#selector(self.confirmationSmsSent),
                                              name: NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS,
                                              object: nil);

And I'm getting

Use of unresolved identifier 'NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS'

Thanks

// EDIT:

I have declared in Obj-C:

NSString *const NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS = @"confirmationSMSSent";

Will this still work with this?

let name: NSNotification.Name = NSNotification.Name("Your_Notification_Name_Key_String") //NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS

And when I use

NotificationCenter.default.addObserver(self, selector:#selector(self.confirmationSmsSent(_:)), name: name, object: nil)

func confirmationSmsSent(notification: NSNotification) {

}

I got error

Value of type 'MyController' has no member 'confirmationSmsSent'

on

NotificationCenter.default.addObserver(self, selector:#selector(self.confirmationSmsSent(_:)), name: name, object: nil)


Solution

  • In Swift 3, the syntax is changed. You have to define the variable of NSNotification.Name

    let name: NSNotification.Name = NSNotification.Name("Your_Notification_Name_Key_String") //NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS
    
    //Add Notification
    NotificationCenter.default.addObserver(self, selector:#selector(self.yourSelector(_:)), name: name, object: nil)
    
    //Remove Notification Observer
    NotificationCenter.default.removeObserver(self, name: name, object: nil)
    
    //Your Selector
    func yourSelector(_ notification: Notification) {
    //Code
    }