Swift代码:如何在收到远程推送通知后启动特定的视图控制器

时间:2015-04-29 01:17:14

标签: ios

在Swift中,我的 main.storyboard 有2个视图控制器(mainVCsecondVC),它们都嵌入在导航控制器中。收到远程推送通知时,如何更改AppDelegate中的代码以使secondV C视图控制器每次启动。我目前有代码在didReceiveRemoteNotification发布通知,并在secondVC中添加代码以添加观察者

AppDelegate.swift中,我的代码如下:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound
    var setting = UIUserNotificationSettings(forTypes: type, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(setting)
    UIApplication.sharedApplication().registerForRemoteNotifications()
    return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    NSNotificationCenter.defaultCenter().postNotificationName("MyNotificationType", object: nil, userInfo: userInfo)

}

secondVC中,我的代码如下:

override func viewWillAppear(animated: Bool) {
    println("viewWillAppear()")
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "AuthenticateWithTouchID:", name: "MyNotificationType", object: nil)
}
override func viewWillDisappear(animated: Bool) {
    println("viewWillDISAPPER")
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "MyNotificationType", object: nil)
}

1 个答案:

答案 0 :(得分:1)

这应该有效。您的UINavigationController的viewControllers属性是嵌入在导航控制器中的所有视图控制器的数组。因此,如果您需要第二个vc,则可以像典型的数组一样访问它,因此viewControllers [1]

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    var navController:UINavigationController = self.window?.rootViewController as! UINavigationController

    if navController.viewControllers != nil {
        var vc:CustomViewController = navController.viewControllers[1] as! CustomViewController
        navController.presentViewController(vc, animated: false, completion: nil)
    }
}