How to properly use CFNotificationCenterAddObserver in Swift for iOS

前端 未结 2 938
面向向阳花
面向向阳花 2020-12-28 20:42

Pulling my hair out getting CFNotificationCenterAddObserver to work in Swift.

        CFNotificationCenterAddObserver(CFNotificationCenterGetDa         


        
2条回答
  •  忘掉有多难
    2020-12-28 21:26

    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)
        }
    }
    

提交回复
热议问题