根据 Core Spotlight 搜索词显示来自 AppDelegate 的可重载视图

Display a relaodable view from AppDelegate based on Core Spotlight search term

我在我的应用程序中设置了 Core Spotlight。我导航到导航控制器中的特定视图控制器,该控制器根据标题显示 webview 网页。例如:

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray *restorableObjects))restorationHandler {

if ([[userActivity activityType] isEqualToString:CSSearchableItemActionType]) {
    // This activity represents an item indexed using Core Spotlight, so restore the context related to the unique identifier.
    // The unique identifier of the Core Spotlight item is set in the activity’s userInfo for the key CSSearchableItemActivityIdentifier.

    NSString *uniqueIdentifier = [userActivity.userInfo objectForKey:CSSearchableItemActivityIdentifier];
    NSString *valueForUID = [self valueForKey:uniqueIdentifier];

    self.tabBar = (UITabBarController *)self.window.rootViewController;
    self.tabBar.selectedIndex = 0;
    UINavigationController *selectedNav=(UINavigationController *)self.tabBar.selectedViewController;
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    WebViewController *webVCVC = [storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
    webVC.title = uniqueIdentifier;
    webVC.titleDetail = valueForUID;
    [selectedNav presentViewController:webVC animated:YES completion:nil];
}
}

简而言之,webVC 根据它的 self.title 和 titleDetail 加载特定网页,这些值会发生变化,因为每个 spotlight 唯一 ID 都不同。

问题不在于第一个聚光灯索引是否 selected,一切正常。 但是,如果我 select 新的 'Back To %@' 按钮并返回到 Spotlight 以 select 一个新的搜索项目,我收到以下错误:

Warning: Attempt to present <WebViewController: 0x7fced37c8be0> on <UINavigationController: 0x7fced403fa00> whose view is not in the window hierarchy!

所以我认为我所要做的就是每次关闭当前视图并重新加载它:

self.tabBar = (UITabBarController *)self.window.rootViewController;
self.tabBar.selectedIndex = 0;
UINavigationController *selectedNav=(UINavigationController *)self.tabBar.selectedViewController;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
WebViewController *webVC = [storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
[webVC dismissViewControllerAnimated:NO completion:^{
   webVC.title = pubNum;
   webVC.titleString = pubTitle;
   [selectedNav presentViewController:webVC animated:YES completion:nil];
}];

这个也不工作,我得到以下warning/error:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior

这是有道理的。在这种特殊情况下我该如何规避这种情况?

A UINavigationController,即使它继承自 UIViewController,也没有自己的非 nil view,因此您不能调用presentViewController:animated:completion: 在上面。我认为您混淆了 presentViewController(显示模式,需要发送到当前正在显示的视图控制器)和 pushViewController:animated:,发送到当前视图控制器的 [=17] =].

我通过从导航控制器中关闭它来修复它:

//Instead of this
[webVC dismissViewControllerAnimated...

//I used this
[selectedNav.presentedViewController dismissViewControllerAnimated...