小编典典

如何发出推送通知打开某个视图控制器?

swift

我查看了SO,但是当您收到推送通知时,我找不到任何讨论的问题,然后如何打开特定的视图控制器。例如,如果您正在创建类似WhatsApp的应用程序,并且收到两个不同的推送通知,即来自两个不同用户的消息,您将如何将其从应用程序委托定向到相应的viewController?

据我在userinfo字典中知道appDelegate给您的,您可以给一个特定的viewController一个ID,但是我不知道如何向一个特定的view
controller致敬,这样您就可以再次指向该viewController 。请在答案中包含一个代码段

*可以接受Swift或Objective-C的答案*


阅读 418

收藏
2020-07-07

共1个答案

小编典典

您可以使用应用程序委托中的此代码检测是否从通知中打开了应用程序。当应用程序处于活动状态UIApplicationStateInactive之前,您需要设置初始视图控制器。您可以在那里执行任何逻辑,以决定应打开哪个视图控制器以及应在该视图控制器中显示哪些内容。

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

    if(application.applicationState == UIApplicationStateActive) {

        //app is currently active, can update badges count here

    } else if(application.applicationState == UIApplicationStateBackground){

        //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here

    } else if(application.applicationState == UIApplicationStateInactive){

        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here

        self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

        UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];

        self.window.rootViewController = viewController;
        [self.window makeKeyAndVisible];

    }

}
2020-07-07