Search code examples
iosswiftnsnotificationcenter

Extending NotificationCenter


I am trying to write an extension for NotificationCenter

I find the syntax a little meaty and "boilerplatey" and would like to provide a simple extension that simplifies posting and observing.

I can dispatch an event like so

NotificationCenter.dispatch(key: <#T##String#>, payload: <#T##[String : String]#>)

However I would like to observe an event in a similar fashion.

I am trying to create something like

NotificationCenter.observe(key: <#T##String#>, handler: <#T##() -> Void#>)

However this is not correct. I am unsure how I can handler passing in my selector function that should be triggered on an observation?

This is my attempt so far.

extension NotificationCenter {
    static func dispatch(key: String, payload: [String: String] = [:]) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: key), object: nil, userInfo: payload)
    }
    static func observe(key: String, handler: ()->Void) {
        NotificationCenter.default.addObserver(
            self, selector: handler, name: NSNotification.Name(rawValue: key), object: nil
        )
    }
}

Solution

  • It sounds like you need something like

    extension NotificationCenter {
        static func dispatch(key: String, payload: [String: String] = [:]) {
            self.default.post(name: NSNotification.Name(rawValue: key), object: nil, userInfo: payload)
        }
        static func observe(key: String, handler: @escaping (Notification) -> Void) {
            self.default.addObserver(forName: NSNotification.Name(rawValue: key), object: nil, queue: .main, using: handler)
        }
    }