IOS Swift- 收到推送通知时,应用程序不会打开特定的选定选项卡栏控制器索引

IOS Swift- App does not open specific selected tab bar controller index when push notification is received

我的应用程序有 5 个选项卡栏,每次我收到推送通知时,我都希望应用程序导航到索引中的第 3 个选项卡。当应用程序处于前台或后台(处于活动状态)时,我能够实现它。如果应用程序已关闭并且我尝试打开推送通知,应用程序将打开并崩溃。 下面是我的代码

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
    let tabbar:UITabBarController = self.window?.rootViewController as! UITabBarController
    tabbar.selectedIndex = 3
}

请让我知道我做错了什么。

尝试在 diFinishLaunchingWithOptions 方法的末尾添加以下代码:

 if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String : AnyObject] {
            _ = notification["aps"] as! [String : AnyObject]

            (window?.rootViewController as! UITabBarController).selectedIndex = 3
        }

你在调试你的代码吗?如果应用在那里崩溃,很可能是 window.rootViewController 不是 UITabBarController。

您可以对其进行调试或更改为!作为? 并且:

tabbar?.selectedIndex = 3

如果应用没有崩溃,则说明您的标签栏控制器在其他地方。找到它就可以了。

另外记得在选项字典中检查您的通知。