ios - 无法在点击通知时正确显示 ViewController

标签 ios objective-c push-notification apple-push-notifications

我正在使用 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 中时进入后台怎么办?结构如下所示:enter image description here

应用程序在“另一个页面”时进入后台,我向我的应用程序发送了一个通知。当我尝试从通知中打开我的应用程序时。控制台告诉我这个:enter image description here

并且无法呈现 infoViewController。有人请帮助我。

最佳答案

错误日志告诉您,您正在尝试从不在前台的 Controller 中显示 InfoViewController,这是正确的,因为已经显示了另一个 Controller 。

我的解决方案:

  1. 创建一个 BaseViewController 类(如果您还没有),该类应该从应用程序的所有 Controller 中扩展。
  2. 在 BaseViewController 中创建一个名为 CURRENT_CONTROLLER 的static UIViewController 属性。
  3. 在 viewDidAppear() 方法中设置 CURRENT_CONTROLLER = self
  4. 如果您在任何 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/

相关文章:

ios - swift - 方法不会覆盖其父类(super class)中的任何方法 & 'UITableView' 没有名为 'viewDidLoad' 的成员

ios - 在 Swift 中使用自定义消息抛出错误/异常的最简单方法?

ios - UILabel 的 TextAlignment

android - 如何折叠 Android 通知?

iphone - 将 Urbanairship 集成到我的 iOS 应用程序中所需的最少文件集是什么?

iphone - 如何从itunes connect解析 "Metadata Rejected"?

ios - PlistBuddy 或代码显示版本信息 iOS

ios - 如何使用 Storyboard 将图像传递给另一个 View Controller

mysql - 将 NSURLConnection 替换为 NSURLSession 以下载和解析 json 提要

android - OneSignal 推送通知点击打开 Activity