Last active
May 22, 2020 21:16
-
-
Save CommanderPho/856f1fb34c3052e0209a00305803f32f to your computer and use it in GitHub Desktop.
Swift NotificationCenter (multicast global event management) Broadcaster/Listener example
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
// 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 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
// 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