Created
June 2, 2022 10:17
-
-
Save jphungcode/d9623e38bb1a5f2f271e2543f8b85dc1 to your computer and use it in GitHub Desktop.
Swift global 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
// 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