Skip to content

Instantly share code, notes, and snippets.

@jphungcode
Created June 2, 2022 10:17
Show Gist options
  • Save jphungcode/d9623e38bb1a5f2f271e2543f8b85dc1 to your computer and use it in GitHub Desktop.
Save jphungcode/d9623e38bb1a5f2f271e2543f8b85dc1 to your computer and use it in GitHub Desktop.
Swift global notifications
// AppDelegate.swift
// subscription listener subscribing to "some-event-name" posted by Electron or other app
func observer() {
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(), Unmanaged.passRetained(self).toOpaque(), observerCallback, "some-event-name" as CFString , nil, .deliverImmediately)
}
// the listener callback - do something when you receive "some-event-name" event.
let observerCallback: CFNotificationCallback = { center , observer, name, object, info in
// perform check on incoming data to see if it exists as a dictionary (object sent from javascript)
if let data = info as? Dictionary<String, Any> {
// Check if value present before using it
guard let method = data["foo"] as? String else { return }
print(method)
// we can also post a event back
postNotification()
} else {
print("Could not parse incoming data")
}
}
func postNotification() {
// create notification event name that other apps will listen to
let notificationName: CFNotificationName = .init(rawValue: "some-event-name" as CFString)
// emit notification with data dictionary with key-value as String types
let data: [String:String] = ["foo":"bar"]
CFNotificationCenterPostNotification(CFNotificationCenterGetDistributedCenter(), NotificationName, nil, data as CFDictionary, true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment