Pulling my hair out getting CFNotificationCenterAddObserver to work in Swift.
CFNotificationCenterAddObserver(CFNotificationCenterGetDa
I wrote this to pass a notification from a Share Extension to it's parent App, when in iPadOS, both could be active simultaneously.
These are placed in a library shared by both the App and the Extension. The App uses the ExtensionListener, the Extension uses the ExtensionEvent.
final public class ExtensionListener: NSObject {
// the inter-process NotificationCenter
private let center = CFNotificationCenterGetDarwinNotifyCenter()
private var listenersStarted = false
fileprivate static let notificationName = "com.example.CrossProcessExtensionAction" as CFString
public override init() {
super.init()
// listen for an action in the Share Extension
startListeners()
}
deinit {
// don't listen anymore
stopListeners()
}
// MARK: listening
fileprivate func startListeners() {
if !listenersStarted {
self.listenersStarted = true
CFNotificationCenterAddObserver(center, Unmanaged.passRetained(self).toOpaque(), { (center, observer, name, object, userInfo) in
// send the equivalent internal notification
NotificationCenter.default.post(name: NSNotification.Name.SomeInternalExtensionAction, object: nil)
}, Self.notificationName, nil, .deliverImmediately)
}
}
fileprivate func stopListeners() {
if listenersStarted {
CFNotificationCenterRemoveEveryObserver(center, Unmanaged.passRetained(self).toOpaque())
listenersStarted = false
}
}
}
final public class ExtensionEvent: NSObject {
public static func post() {
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFNotificationName(rawValue: ExtensionListener.notificationName), nil, nil, true)
}
}