3D触摸快速操作预览视图控制器只有一次

时间:2015-12-02 18:08:50

标签: ios swift 3dtouch quickaction

我有以下问题。当我在手机上运行我的应用程序时,3d触摸图标并选择快速操作它启动应用程序呈现正确的视图控制器但是当我将应用程序放在后台并尝试调用快速操作时它只是打开应用程序我在哪里留下它。所以要使它工作,我每次都要杀了我的应用程序。 这是我的代码:

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
    if shortcutItem.type == "com.traning.Search" {

        let sb = UIStoryboard(name: "Main", bundle: nil)

        let searchVC = sb.instantiateViewControllerWithIdentifier("searchVC") as! UINavigationController

        let root = UIApplication.sharedApplication().keyWindow?.rootViewController
        root?.presentViewController(searchVC, animated: false, completion: { () -> Void in
            completionHandler(true)
        })

    }
}

提前致谢。

1 个答案:

答案 0 :(得分:4)

我猜你正试图从一个看不到的视图控制器中呈现一个视图控制器。您可以使用以下扩展程序:

    extension UIViewController {
    func topMostViewController() -> UIViewController {
        if self.presentedViewController == nil {
            return self
        }
        if let navigation = self.presentedViewController as? UINavigationController {
            return navigation.visibleViewController.topMostViewController()
        }
        if let tab = self.presentedViewController as? UITabBarController {
            if let selectedTab = tab.selectedViewController {
                return selectedTab.topMostViewController()
            }
            return tab.topMostViewController()
        }
        return self.presentedViewController!.topMostViewController()
    }
}

extension UIApplication {
    func topMostViewController() -> UIViewController? {
        return self.keyWindow?.rootViewController?.topMostViewController()
    }
}

您可以将这两者放在应用委托类上方的app delegate.swift中,以获取当前可见的视图控制器。enter image description here然后在其上显示搜索视图控制器。例如:

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
    if shortcutItem.type == "com.traning.Search" {

        let sb = UIStoryboard(name: "Main", bundle: nil)

        let searchVC = sb.instantiateViewControllerWithIdentifier("searchVC") as! UINavigationController

        let topViewController = UIApplication.sharedApplication.topMostViewController()
        topViewController.presentViewController(searchVC, animated: false, completion: { () -> Void in
            completionHandler(true)
        })

    }
}