通过推送通知打开特定的ViewController

时间:2017-07-15 07:22:36

标签: ios swift push-notification

我在触发推送通知方面遇到了一些麻烦。当用户点击具有一些有效负载的通知时,我需要打开特定的VC。考虑到应用程序是背景的情况我使用此代码

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

        if ((application.applicationState == .inactive || application.applicationState == .background)) {

            //open specific VC depends on notification payload
        }
    }

这里的问题开始了:1)我不能从AppDelegate推送VC,只能通过设置新的rootController 2)我必须使用来自AppDelegate的代码的didReceiveRemoteNotification方法

1 个答案:

答案 0 :(得分:3)

请参阅此答案:How to make your push notification Open a certain view controller?

在AppDelegate中使用此代码来检测应用程序是否从通知中打开。在应用程序变为活动状态之前,请在应用程序状态为 UIApplicationStateInactive 时设置初始VC。编写代码以设置VC以及VC中的内容。

-(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];

    }

}