在 Spotlight 搜索后显示细节视图控制器

Show detail view controller after spotlight search

在最近的一个项目中,我实现了 Spotlight 搜索并且一切正常(我使用了 UINavigationController)。现在我正在回收 Spotlight 搜索另一个不包含 UINavigationController 而只包含两个 UIViewController 的项目。同样在这种情况下,除了在聚光灯搜索中按下特定项目时重定向到详细视图控制器外,一切正常。我发现问题出在这个方法中,这是因为我没有使用 UINavigationController。所以我的问题是,如何更改此代码以仅与我的两个 UIViewController 一起使用?

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Swift.Void) -> Bool {

    let navController = self.window!.rootViewController as! UINavigationController

    if let actID = userActivity.userInfo!["kCSSearchableItemActivityIdentifier"] as? String {
        let ricette = DataManager.shared.arra.filter { [=10=].id.uuidString == actID }
        if let ricetta = ricette.first {
            debugPrint("Abbiamo la ricetta grazie all'ID")

            if let listController = navController.topViewController as? ListController {

                if let posizione = DataManager.shared.arra.index(of: ricetta) {
                    listController.showDetailFromSpotlightSearch(posizione)
                }

            } else if let ricettaController = navController.visibleViewController as? RicettaController {
                ricettaController.ricetta = ricetta
                ricettaController.aggiornaInterfaccia()
            }

        } else { debugPrint("errore ID") }
    } else { debugPrint("errore ID") }

    return true
}

您应该使用这两个扩展来确定 topViewController 和 visibleViewController:

extension UIApplication {
class func getVisibleViewController(_ rootViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    if let presentedViewController = rootViewController?.presentedViewController {
        return getVisibleViewController(presentedViewController)
    }

    return rootViewController
}}

extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    if let presented = controller?.presentedViewController {
        return topViewController(controller: presented)
    }
    return controller
}}