Created
March 31, 2017 16:39
-
-
Save bhrott/e6921339a662fccb7c22f362e1676964 to your computer and use it in GitHub Desktop.
Swift :: Service for Notifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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