我正在使用 Objective-C
。我想显示一个包含通知内容的 infoViewController
。
这是我的代码:
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[self presentViewControllerWithUserInfo:userInfo];
}
- (void)presentViewControllerWithUserInfo:(NSDictionary *)userInfo {
infoViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"info"];
vc.infoString = [[userInfo objectForKey:@"info"] objectForKey:@"string"];
//NSLog(@"class: %@", [self.window.rootViewController class]);
[self.window.rootViewController presentViewController:vc animated:YES completion:nil];
}
我通过 rootViewController
显示 infoViewController
。但是,如果 App 在不在 rootViewController
中时进入后台怎么办?结构如下所示:
应用程序在“另一个页面”时进入后台,我向我的应用程序发送了一个通知
。当我尝试从通知中打开我的应用程序时。控制台告诉我这个:
并且无法呈现 infoViewController
。有人请帮助我。
最佳答案
错误日志告诉您,您正在尝试从不在前台的 Controller 中显示 InfoViewController,这是正确的,因为已经显示了另一个 Controller 。
我的解决方案:
- 创建一个 BaseViewController 类(如果您还没有),该类应该从应用程序的所有 Controller 中扩展。
- 在 BaseViewController 中创建一个名为 CURRENT_CONTROLLER 的static UIViewController 属性。
- 在 viewDidAppear() 方法中设置 CURRENT_CONTROLLER = self。
- 如果您在任何 View Controller 中覆盖此方法,请记住始终调用 super.viewDidAppear()。
然后,当您收到远程通知时,执行如下操作:
infoViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"info"];
vc.infoString = [[userInfo objectForKey:@"info"] objectForKey:@"string"];
if (BaseViewController.CURRENT_CONTROLLER != nil) {
[BaseViewController.CURRENT_CONTROLLER presentViewController:vc animated:YES completion:nil];
} else {
// app just started, your code works well
// this code could never be executed if you extend BaseViewController from all your view controllers
}
关于ios - 无法在点击通知时正确显示 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38199127/