Search code examples
objective-cswiftnsnotificationcenternotificationcenter

How to add an observer in Objective-C and fire a Notification in Swift 3


I have a notification observer in an Objective C file and I want to fire a notification in a Swift 3 file. Since in Objective C the notification name is a NSString but in Swift 3 it's Notification.Name, how can I get the Obj-C observer to catch the Swift fire?

Swift Trigger

NotificationCenter.default.post(name: .notificationName, object: nil, userInfo: nil)

extension Notification.Name {
    static let notificationName = Notification.Name("Test")
}

Obj-C Observer

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(displayError:)
                                      name:"Test"
                                      object:nil];

Solution

  • You would trigger the notification like this:

    NotificationCenter.default.post(
        name: Notification.Name(rawValue: "SomeNotification"),
        object: nil,
        userInfo: nil
    )