在AppDelegate中使用推送通知重定向视图

时间:2015-06-03 10:15:43

标签: ios swift cocoa-touch push-notification uistoryboardsegue

我的目标是编写一个代码,当用户获得推送通知时,我希望将该用户重定向到另一个视图。 如果用户提供了推送通知,并且他是第一次查看控制器(欢迎主屏幕等(但未登录))

var rootViewController = self.window!.rootViewController as! ViewController
rootViewController.performSegueWithIdentifier("hospitalSegue", sender: self)

这几行代码正在运行,但是,如果用户已经在另一个视图控制器(登录/登录/用户页面等)中,则这段代码不起作用并重定向。 我尝试了一切,但仍然无法提出解决方案。我的最终目标是:

if let rootViewController = self.window!.rootViewController as? ViewController
{
    var rootView: UserViewController = UserViewController()

    if let window = self.window{
        window.rootViewController = rootView
    }

    rootViewController.performSegueWithIdentifier("hospitalSegue", sender: self)
    println(self.window?.rootViewController)
}

任何人都可以给我一个想法吗?

2 个答案:

答案 0 :(得分:1)

答案代码是Objective-C,我想谈谈逻辑。要执行此操作,在创建推送通知时,必须设置 userInfo 值以使用推送通知传递数据。

使用此委托方法:application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

您可以通过处理 userInfo

来决定要显示哪个视图
NSDictionary *segueDictionary = [userInfo valueForKey:@"aps"];

NSString *segueName=[[NSString alloc]initWithFormat:@"%@",[segueDictionary valueForKey:@"segueName"]];

if([segueName isEqualToString:@"hospitalSegue"]) 
{
// implement your code to redirect
}

答案 1 :(得分:0)

答案代码是Objective-C,您可以使用以下方法从app delegate prentviewcontroller我使用下面的代码解决了这个问题:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
      [[self topViewController]presentViewController:nav animated:YES    completion:nil];
}

- (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}