Skip to content

Instantly share code, notes, and snippets.

@bhrott
Created March 31, 2017 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhrott/e6921339a662fccb7c22f362e1676964 to your computer and use it in GitHub Desktop.
Save bhrott/e6921339a662fccb7c22f362e1676964 to your computer and use it in GitHub Desktop.
Swift :: Service for Notifications
import Foundation
class NotificationService {
static private var _instance: NotificationService! = nil
static var sharedInstance: NotificationService {
get {
if NotificationService._instance == nil {
NotificationService._instance = NotificationService()
}
return NotificationService._instance
}
}
private init() {}
func post(name: String!, data: Any?) {
NotificationCenter.default.post(name: self.buildEventName(name), object: data)
}
func on(name: String!, handler: @escaping (Notification) -> Void) -> NSObjectProtocol{
return NotificationCenter.default.addObserver(forName: self.buildEventName(name),
object: nil,
queue: nil,
using: handler)
}
func remove(observer: NSObjectProtocol) {
NotificationCenter.default.removeObserver(observer)
}
private func buildEventName(_ name: String!) -> Notification.Name {
return NSNotification.Name(rawValue: name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment