Search code examples
iosswiftcorespotlight

Show detail view controller after spotlight search


in a recent project I implemented the spotlight search and everything works fine (I used a UINavigationController). Now I'm recycling the spotlight search for another project that doesn't contain a UINavigationController but just two UIViewController. Also in this case, everything works fine except the redirection to the detail view controller when a specific item is pressed in the spotlight search. I found out that the problem is in this method and it's because I don't use a UINavigationController. So my question is, how can I change this code to work with only my two 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 { $0.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
}

Solution

  • You should use this two extension to determine the topViewController and the 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
    }}