OStack程序员社区-中国程序员成长平台

标题: ios - 在 Appdelegate.m 的后台线程上发送 NSNotification [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:31
标题: ios - 在 Appdelegate.m 的后台线程上发送 NSNotification

我正在接收远程通知。我想发布一个 nsnotification。我可以发布通知,但我无法在当前的 View Controller 中接收它。

这是我的代码。

我知道这会被调用:

AppDelegate.m

 - (void)applicationUIApplication *)application didReceiveRemoteNotificationNSDictionary *)userInfo
 {

 [[NSNotificationCenter defaultCenter] postNotificationName:CHAT_MESSAGE_RECEIVED object:nil userInfo:messageIdDict];

 }

在调用上述代码之前调用它

MyViewController.m

 -(void)viewWillAppearBOOL)animated
 {

 [[NSNotificationCenter defaultCenter] addObserver:self
                                         selectorselector(messageReceived
                                             name:CHAT_MESSAGE_RECEIVED
                                           object:self];

 }

 -(void)messageReceivedNSDictionary *)userInfo
 {
      NSLog(@"Logged");
 }



Best Answer-推荐答案


我会这样做:

在 AppDelegate 中:

- (void)applicationUIApplication *)application 
didReceiveRemoteNotificationNSDictionary *)userInfo
 {

 [[NSNotificationCenter defaultCenter] postNotificationName:CHAT_MESSAGE_RECEIVED              
                                                     object:messageIdDict 
                                                   userInfo:nil];

 }

在 MyViewController 中:

-(void)viewWillAppearBOOL)animated
 {

 [[NSNotificationCenter defaultCenter] addObserver:self
                                          selectorselector(messageReceived
                                              name:CHAT_MESSAGE_RECEIVED
                                            object:nil];

 }

 -(void)messageReceivedNSNotification *)notification
 {
      NSDictionary *userInfo = NSDictionary dictionaryWithDictionary:[notification object]];
      NSLog(@"Logged");
 }

希望对你有帮助

关于ios - 在 Appdelegate.m 的后台线程上发送 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609803/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4