Skip to content

Instantly share code, notes, and snippets.

@CommanderPho
Last active May 22, 2020 21:16
Show Gist options
  • Save CommanderPho/856f1fb34c3052e0209a00305803f32f to your computer and use it in GitHub Desktop.
Save CommanderPho/856f1fb34c3052e0209a00305803f32f to your computer and use it in GitHub Desktop.
Swift NotificationCenter (multicast global event management) Broadcaster/Listener example
// This example class registers to receive specific NotificationCenter events and responds to them
class ListeningExampleClass {
private var aNotificationCenterObservation: NSObjectProtocol?
// Called for example in .viewDidLoad() or initializer to register for notifications
func subscribeNotifications() {
let center = NotificationCenter.default
self.aNotificationCenterObservation = center.addObserver(forName: .eventActiveWorkspaceChanged, object: nil, queue: nil) { _ in
// Handle event broadcast stuff here...
}
}
}
// This is where the notifications are defined.
extension Notification.Name {
static var eventActiveWorkspaceChanged = NSNotification.Name("eventActiveWorkspaceChangedNotification")
}
// This example class broadcasts events via the NotificationCenter
class BroadcastingExampleClass {
// Posts a notification when the event happens.
func notifyActiveWorkspaceChanged() {
NotificationCenter.default.post(name: .eventActiveWorkspaceChanged, object: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment