我只是想弄清楚如何实施您提到的第一种方法,并从https://www.hackingwithswift.com/read/32/4/how-to-add-core-spotlight-to-找到了一个有用的开始index-your-app-content
他的代码是:
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
if userActivity.activityType == CSSearchableItemActionType {
if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
if let masterVC = navigationController.topViewController as? MasterViewController {
masterVC.showTutorial(Int(uniqueIdentifier)!)
}
}
}
return true
}
我发现self.window?.rootViewController 为?yourRootViewControllerClass是您问题的一个很好的跳板。
我的代码非常基本,如下所示:
// create a storyBoard item to instantiate a viewController from. If you have multiple storyboards, use the appropriate one. I just have one so it is "Main"
let sb = UIStoryboard(name: "Main", bundle: nil)
// get the navigation controller from the window and instantiate the viewcontroller I need.
if let viewController = sb.instantiateViewControllerWithIdentifier("DetailViewController") as? ViewController,
let nav = window?.rootViewController as? UINavigationController {
viewController.setupController(bookName)// setup the viewController however you need to. I have a method that I use (I grabbed the bookName variable from the userActivity)
nav.pushViewController(viewController, animated: false)//use the navigation controller to present this view.
}
这对我有用,但我必须警告一下。我的应用程序只有一个带有三个视图控制器(NavController->tableViewController->ViewController)的故事板。我不确定这个逻辑将如何在更复杂的应用程序上工作。
另一个很好的参考是: http: //www.appcoda.com/core-spotlight-framework/
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
let viewController = (window?.rootViewController as! UINavigationController).viewControllers[0] as! ViewController
viewController.restoreUserActivityState(userActivity)
return true
}
那个 viewController 有这个方法:
override func restoreUserActivityState(activity: NSUserActivity) {
if activity.activityType == CSSearchableItemActionType {
if let userInfo = activity.userInfo {
let selectedMovie = userInfo[CSSearchableItemActivityIdentifier] as! String
selectedMovieIndex = Int(selectedMovie.componentsSeparatedByString(".").last!)
performSegueWithIdentifier("idSegueShowMovieDetails", sender: self)
}
}
}