David David - 6 months ago 29
Swift Question

How to handle static QuickActions for iOS app using ViewControllers managed by a TabBarController in Xcode written in Swift

I already created some (static) QuickActions in Info.plist for my iOS app created in Xcode and written in Swift.

I have problems with making them able to open a ViewController. Of cause, I already googled, but nothing worked for me. If this counts: I'm using ViewController managed by a TabBarController. Most tutorials seem to use NavigationController. But, I think it will be done with the segues, right? What code do I need to handle it?

Can anybody provide it please? Or does anybody know a simple manual/tutorial?

Regards, David.

P.S.:
I tried this code, but it seems to work only with NavigationController?!
Code:

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void)
{
self.handleShortcutItem(shortcutItem)
completionHandler(true)
}

func handleShortcutItem(shortcutItem: UIApplicationShortcutItem)
{
switch shortcutItem.type {
case "icons.quickaction.home":
self.presentComposeViewController()
default: break
}
}

func presentComposeViewController()
{
guard let navigationController = window?.rootViewController as? UINavigationController else { return }

let identifier = "MyViewController"
let composeViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(identifier)

navigationController.pushViewController(composeViewController, animated: false)
}

Answer

I finally found the solution with the help from @ILikeTau.

I'm using the following code to open my ViewControllers managed by a TabBarController with QuickAction:

@available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {

    if(shortcutItem.type == "app.quickaction.search"){
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        window?.rootViewController = vc
        guard let tabBarController = window?.rootViewController as? UITabBarController else { return };
                tabBarController.selectedIndex = 2
    }
    else if(shortcutItem.type == "app.quickaction.home"){
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        window?.rootViewController = vc
        guard let tabBarController = window?.rootViewController as? UITabBarController else { return };
        tabBarController.selectedIndex = 0
    }
}

This code works from both modes: app is in background mode and app is closed. I think this way is easier and shorter than the common way with multiple functions.