从主应用发布的“今日"小部件中的“观察通知" [英] Observing Notification in Today Widget which is posted from main app
问题描述
我在一个快速文件中声明了通知名称,该文件具有主应用和今天的小部件的目标成员资格:
I have declared notification name in a swift file which has target membership of both main app and today widget:
let SpecialKey = Notification.Name("howLongNotif")
然后在我的主应用程序视图控制器中,当位置更新(位置更新的后台模式处于启用状态)时,我将发布通知:
Then in my main app view controller, I am posting notification when location is updated (background mode for location updates is on):
NotificationCenter.default.post(name: SpecialKey, object: nil, userInfo: nil)
在我今天的窗口小部件viewDidLoad中,我这样观察它:
In my today widget viewDidLoad, I am observing it like this:
NotificationCenter.default.addObserver(self, selector: #selector(TodayViewController.dataReceived), name: SpecialKey, object: nil)
并具有:
func dataReceived(_notification: NSNotification) {
print("data received")
}
但是永远不会调用dataReceived
函数.
But dataReceived
function is never invoked.
我通过将观察者和dataReceived函数移至主应用程序进行了测试,并且在该应用程序中可以正常工作.
I tested by moving the observer and dataReceived function to main app and it works fine there.
推荐答案
您的主应用程序(今天是扩展程序)在电话上作为单独的进程运行. NSNotificationCenter
仅在单个进程中起作用.
Your main app and today is extension are run as separate processes on the phone. NSNotificationCenter
only works within a single process.
要在扩展程序和主应用之间传递信息,可以使用NSUserDefaults
或共享容器中的文件.
To pass information between your extension and main app, you can use NSUserDefaults
or a file in the shared container.
这篇关于从主应用发布的“今日"小部件中的“观察通知"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!