0

I started new swift project recently. I wanted to simplify usage of notifications and notification observers, so wrote some code for that. So I wanted to share this code and also ask about any possible issues?

Event, class which post event to notification center

import Foundation

enum EventName: String {
    case ProfileUpdate
    case ApplicationDidPreload
}

class Event {

    static let shared: Event = Event()

    /// Post event to notification center
    /// - Parameter event: event name to post
    /// - Parameter object: data you're going to pass
    /// - Parameter userInfo: user info
    func post(event: EventName, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil) {
        let notification: Notification = Notification(name: Notification.Name(rawValue: event.rawValue), object: object, userInfo: userInfo)
        NotificationCenter.default.post(notification)
    }
}

Event listener class, with a couple of methods to observe notification. I wanted to handle both cases when data is passed to notification or not.

import Foundation

class EventListener {

    typealias callback = () -> ()
    typealias callbackWithData = (_ data: Any) -> ()

    static let shared: EventListener = EventListener()
    private var callback: callback?
    private var callbackWithData: callbackWithData?

    /// Listen event which not return any data in callback closure
    /// Parameter event: event name to listen
    /// Parameter callback: callback closure
    func listenEvent(event: EventName, callback: @escaping callback) {
        self.callback = callback
        self.addObserver(event: event)
    }

    /// Listen event which returns data in callback closure
    /// Parameter event: event name to listen
    /// Parameter callback: callback closure
    func listenEvent(event: EventName, callbackWithData: @escaping callbackWithData) {
        self.callbackWithData = callbackWithData
        self.addObserver(event: event)
    }

    /// Add and setup observer to notification center
    private func addObserver(event: EventName) {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.handler),
                                               name: NSNotification.Name(rawValue: event.rawValue),
                                               object: nil)
    }

    /// Handle notification observer
    @objc private func handler(notification: Notification) {
        guard let data = notification.object else {
            self.callback?()
            return
        }

        self.callbackWithData?(data)
    }
}

Example of usage

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            Event.shared.post(event: .ApplicationDidPreload)
            Event.shared.post(event: .ProfileUpdate, object: 1)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        EventListener.shared.listenEvent(event: .ApplicationDidPreload, callback: self.test1)
        EventListener.shared.listenEvent(event: .ProfileUpdate, callbackWithData: self.test2)
    }

    private func test1() {
        print("preloaded")
    }

    private func test2(data: Any) {
        print("profile id")
        let Id: Int? = data as? Int
        print(Id)
    }
}
Vadims Krutovs
  • 197
  • 2
  • 3

1 Answers1

1

IMHO the Event class for posting to the notification center is not necessary, it's better to extend Notification.Name like

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

which enables you to just use .MyNotificationName as notification name.

For using a block when listening to a notification, you could also use the existing block based version of an observer:

func addObserver(forName name: NSNotification.Name?, 
                   object obj: Any?, 
                        queue: OperationQueue?, 
                  using block: @escaping (Notification) -> Void) -> NSObjectProtocol
TheEye
  • 9,280
  • 2
  • 42
  • 58