0

每当触发本地通知并执行其自定义操作时,我想打开一个特定ViewController的。我使用了以下代码行:TabBarController

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    switch response.actionIdentifier {
    case "first":
        DispatchQueue.main.async(execute: {
            self.first()
        })
    case "second":
        DispatchQueue.main.async(execute: {
            self.second()
        })
    default:
        break
    }


    completionHandler()
}

所以这是一个first() 功能

 func first() {


    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    let tabBarController = storyboard.instantiateViewController(withIdentifier: "Root") as! UITabBarController
    let navigationController = storyboard.instantiateViewController(withIdentifier: "First") as! UINavigationController

    tabBarController.present(navigationController, animated: true) { 

    }

    self.window = UIWindow.init(frame: UIScreen.main.bounds)
    self.window?.tintColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
    self.window?.rootViewController = tabBarController
    self.window?.makeKeyAndVisible()

}

第二个功能second()

func second() {


    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    let tabBarController = storyboard.instantiateViewController(withIdentifier: "Root") as! UITabBarController
    let navigationController = storyboard.instantiateViewController(withIdentifier: "Second") as! UINavigationController

    tabBarController.present(navigationController, animated: true) {

    }

    self.window = UIWindow.init(frame: UIScreen.main.bounds)
    self.window?.tintColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
    self.window?.rootViewController = tabBarController
    self.window?.makeKeyAndVisible()

}

ViewController而且效果很好,但是在显示第一个并触发第二个通知时,我无法打开第二个:在控制台中:警告尝试显示 ViewController ...

4

2 回答 2

2

用这个:

tabBarController.selectedIndex = 1

或这个:

tabBarController.selectedViewController = tabBarController.viewControllers![1]

其中1可以是viewcontrollers您提供的任何tabBarController

于 2017-02-15T03:01:32.977 回答
1

我遇到了类似的问题,更改selectedIndex对我不起作用。根据项目的要求,您可以实例化您的ViewController并将其添加为 aSubview并移至该Subview. 完成后,请确保将其删除Subview

let replyView = self.storyboard?.instantiateViewControllerWithIdentifier("replyView")
    self.addChildViewController(replyView!)
    self.view.addSubview(replyView!.view)
    replyView!.didMoveToParentViewController(self)
于 2017-02-15T03:15:27.780 回答