【发布时间】:2015-01-16 23:13:45
【问题描述】:
我有一个使用本地通知的应用。直到最近一切正常,但在 iOS 8 发布后,当应用程序未运行(从进程中删除)时,我的本地通知不起作用。这是我在应用委托中设置本地通知的代码。
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[[NSNotificationCenter defaultCenter] postNotificationName:localReceived object:self userInfo:notification.userInfo];
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
{
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
else if ([UIApplication instancesRespondToSelector:@selector(registerForRemoteNotificationTypes:)])
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
...
// Local notificaiton example. Icon badge
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSLog(@"locationNotification:%@",locationNotification.alertBody);
if (locationNotification) {
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
// call local notification method
[self application:[UIApplication sharedApplication] didReceiveLocalNotification:locationNotification];
}
return YES;
}
当我的应用程序未运行时,会调用 didFinishLaunchingWithOptions: 方法。在其中我再次调用 didReceiveLocalNotification 方法,我调用 postNotificationName。我将观察者放在我的 ViewControllers ViewDidLoad 方法中:
- (void)viewDidLoad
{
...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(recieveLocalNotification:) name:localReceived object:nil];
...
}
问题在于,当应用未运行时,永远不会调用 recieveLocalNotification: 方法。每次应用程序处于后台或运行时都会调用它。谁能告诉我我在这里做错了什么? 提前致谢!
【问题讨论】:
-
如果您的应用程序没有运行并重新启动到后台,那么您的 viewController 将不会被实例化,因此它无法接收到通知。
-
嗨@Paulw11,感谢您的快速回复!我正在使用的 VC 在 didFinishLaunchingWithOptions 方法中实例化(其中 3 个点在我的代码 sn-p 中)。莫非还是太快了?我能做些什么来规避taht?添加一个 NSTimer?
-
为什么不直接调用方法而不是依赖通过NSNotificationcentre解耦呢?
-
好吧,事实是我对 iOS 开发还很陌生,我不确定这是如何完成的。我能麻烦你在评论中给我写几行代码吗?
-
一旦你加载了viewController,假设它在一个变量
myVC你会说[myVC theMethodToCall]
标签: ios objective-c ios8 uilocalnotification