应用程序终止后,使用NSNotification在UIViewController中处理UILocalNotification

我正在使用UILocalNotification ,我想通知我的控制器之一,即使应用程序已被终止,通知已收到。

在我的appDelegate中,我实现了这个function:

 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { if ([application applicationState] == UIApplicationStateInactive) { [[NSNotificationCenter defaultCenter] postNotificationName:@"localNotificationReceived" object:notification.userInfo]; } } 

在我的UIViewController我在viewDidLoad方法上实现了观察者

 - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didlocalNotificationReceived:) name:@"localNotificationReceived" object:nil]; } 

它运行在后台运行的应用程序完美。 由于viewDidLoad方法已经被调用,Observer正在等待..

问题是当我杀了应用程序。 然后,我的控制器的观察者不见了, didlocalNotificationReceived方法从不被调用。

我认为这是因为当我收到localNotification并再次运行应用程序。 didReceiveLocalNotification:方法在我的UIViewControllerviewDidLoad之前调用。 然后在PostNotificationName之后创build观察者,然后观察者不收到任何东西。

我想知道是否有一些最佳实践或模式来处理这类问题。

我知道didFinishLaunchingWithOptions方法是在didlocalNotificationReceived之前didlocalNotificationReceived因此可能有些事情要做。

更新:

我也发现,当应用程序被终止。 一旦你点击通知,它打开应用程序,调用函数didFinishLaunchingWithOptions但从来没有调用didReceiveLocalNotification 。 所以我认为我会处理两种情况。

好的,我find了答案。

实际上,我手动初始化我的故事板,并谨慎,我发布NSNotification之前初始化我的主视图

我的didFinishLaunchingWithOptions:方法看起来像这样:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]; UIViewController *vc =[storyboard instantiateInitialViewController]; //call the initWithCoder: method of my controller if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) { UILocalNotification *localNotification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]; [[NSNotificationCenter defaultCenter] postNotificationName:@"localNotificationReceived" object:localNotification.userInfo]; } self.window.rootViewController = vc; [self.window makeKeyAndVisible]; return YES; } 

然后在我的UIViewController我在initWithCoder:方法而不是viewDidLoad:创buildNSNotification观察者viewDidLoad:

 - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didlocalNotificationReceived:) name:@"localNotificationReceived" object:nil]; } return self; } - (void)didlocalNotificationReceived:(NSNotification *)notification { //Execute whatever method when received local notification } 

而当应用程序没有被杀害,我仍然使用didReceiveLocalNotification:方法:

 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { if ([application applicationState] == UIApplicationStateInactive) { [[NSNotificationCenter defaultCenter] postNotificationName:@"localNotificationReceived" object:notification.userInfo]; } } 

我不确定这是否是最佳做法。 但它运作良好!

希望它会帮助:)