ios 将通知推送到特定的视图控制器

ios push notifications to a specific view controller

我的应用程序接收远程推送通知,并且在收到它们后,我想将它带到特定的视图控制器(几乎所有时间)。我见过这样的代码(在 didReceiveRemoteNotification 上)。我正在为我的应用程序使用故事板。

    UIViewController *vc = self.window.rootViewController;
    PushViewController *pvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"someid"];
    [vc presentViewController:pvc animated:YES completion:nil];

这看起来很简单。但是它会对内存分配有任何影响吗,因为看起来每次推送通知到达时,我们都在实例化一个新的视图控制器。这是最佳做法吗?

您可以尝试类似的方法:

    PushViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"someid"];

   [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];

您不需要每次都将 uiviewcontroller 分配为 rootview,除非您想让 uiviewcontroller 呈现您的 pushVC。

如果您在应用程序委托中执行此操作,请通过以下方式获取故事板参考:

  UIStoryboard *test=[UIStoryboard storyboardWithName:@"name" bundle:nil];

然后调用

  [test instantiateViewControllerWithIdentifier.....

上面你提到的代码没问题。但是逻辑仍然取决于您如何处理。如果您的推送通知总是想要不同的 VC,那没问题。

假设您立即收到两个推送通知,其中两个 VC 将立即显示。但是你只想要一个屏幕来进行 Push 那么这就会有麻烦了。

如果你想拥有一个 pushViewController 对象,那么你可以将它设为一个全局对象并像这样进行简单的检查

UIViewController *vc = self.window.rootViewController;
if(!pvc)
{
   pvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"someid"];
}
[vc updatePushViewControllerDependingOnPushNotificationObject:somePushObject];
[vc presentViewController:pvc animated:YES completion:nil];