Observing Notification in Today Widget which is posted from main app

天大地大妈咪最大 提交于 2019-12-13 03:58:44

问题


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)

In my today widget viewDidLoad, I am observing it like this:

NotificationCenter.default.addObserver(self, selector: #selector(TodayViewController.dataReceived), name: SpecialKey, object: nil)

and have:

func dataReceived(_notification: NSNotification) {
    print("data received")
}

But dataReceived function is never invoked.

I tested by moving the observer and dataReceived function to main app and it works fine there.


回答1:


Your main app and today is extension are run as separate processes on the phone. NSNotificationCenter only works within a single process.

To pass information between your extension and main app, you can use NSUserDefaults or a file in the shared container.



来源:https://stackoverflow.com/questions/45986695/observing-notification-in-today-widget-which-is-posted-from-main-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!