How to communicate between iOS App Containing Extension and Extension (not Host App)

后端 未结 4 1410
攒了一身酷
攒了一身酷 2021-01-30 17:46

TLDR: Is it possible to send realtime messages or notifications between iOS App and it\'s Extension?

I\'m writing an iOS App with an extension

4条回答
  •  情深已故
    2021-01-30 18:17

    There is a hack that you can use to communicate between any two apps in iOS or app and extension. The only thing - it doesn't work with NetworkExtension since Apple is blocking any I/O in it.

    You can post notification to the DarwinNotificationCenter this way:

        let notificationName = CFNotificationName("com.notification.name" as CFString)
        let notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
    
        CFNotificationCenterPostNotification(notificationCenter, notificationName, nil, nil, false)
    

    In your app add observer:

        let notificationName = "com.notification.name" as CFString
        let notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
    
        CFNotificationCenterAddObserver(notificationCenter,
                                        nil,
                                        { (
                                            center: CFNotificationCenter?,
                                            observer: UnsafeMutableRawPointer?,
                                            name: CFNotificationName?,
                                            object: UnsafeRawPointer?,
                                            userInfo: CFDictionary?
                                            ) in
    
                                            print("Notification name: \(name)")
                                        },
                                        notificationName,
                                        nil,
                                        CFNotificationSuspensionBehavior.deliverImmediately)
    

    Some links: https://github.com/choefele/CCHDarwinNotificationCenter

    https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot

    https://developer.apple.com/library/content/documentation/Darwin/Conceptual/MacOSXNotifcationOv/DarwinNotificationConcepts/DarwinNotificationConcepts.html

提交回复
热议问题