Swift - pushViewController из appDelegate, rootViewController.navigationController - nil
Проблема с несколькими руководствами, в частности
http://blog.originate.com/blog/2014/04/22/deeplinking-in-ios/
Я устанавливаю схему URL и хорошо работаю, чтобы запустить приложение из другого приложения, но передача в хост или URL не работает, как кажется. Я использую раскадровки и конструктор интерфейсов для всех макетов представления.
В руководстве показан этот openURL в appDelegate:
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
if([[url host] isEqualToString:@"page"]){
if([[url path] isEqualToString:@"/page1"]){
[self.mainController pushViewController:[[Page1ViewController alloc] init] animated:YES];
}
return YES;
}
}
Вот моя версия упрощена и быстро от нескольких других источников, т.е.
Получить экземпляр ViewController из AppDelegate в Swift Я пропускаю условное выражение для хоста url на данный момент, чтобы удалить потенциальные другие переменные в проблеме.
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
var rootViewController = self.window!.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var profileViewController = mainStoryboard.instantiateViewControllerWithIdentifier("profile") as ProfileViewController
rootViewController.navigationController.popToViewController(profileViewController, animated: true)
return true
}
Быстрая версия вызывает сбой:
fatal error: unexpectedly found nil while unwrapping an Optional value
Кажется, что rootViewController еще не имеет навигационного контроллера?
Ответы
Ответ 1
Кажется, что rootViewController на самом деле имеет тип UINavigationController в моем случае, поэтому его включение в объявление разрешило мне напрямую вызвать pushToViewController.
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
var rootViewController = self.window!.rootViewController as UINavigationController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var profileViewController = mainStoryboard.instantiateViewControllerWithIdentifier("profile") as ProfileViewController
rootViewController.pushToViewController(profileViewController, animated: true)
return true
}
Ответ 2
В одной строке кода:
Swift 3:
self.navigationController!.pushViewController(self.storyboard!.instantiateViewController(withIdentifier: "view2") as UIViewController, animated: true)
self.navigationController!.pushViewController(self.storyboard!.instantiateViewControllerWithIdentifier("view2") as UIViewController, animated: true)
Ответ 3
APPDELEGATE TO PAGE:
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loginPageView = mainStoryboard.instantiateViewControllerWithIdentifier("leadBidderPagerID") as! LeadBidderPage
var rootViewController = self.window!.rootViewController as! UINavigationController
rootViewController.pushViewController(loginPageView, animated: true)
СТРАНИЦА НА СТРАНИЦУ:
let loginPageView = self.storyboard?.instantiateViewControllerWithIdentifier("scoutPageID") as! ScoutPage
self.navigationController?.pushViewController(loginPageView, animated: true)
Ответ 4
Обновлен для быстрых 3/4.
Самая проголосовавшая "одна строка кода" не работает, потому что нет контроллера навигации в "я"
let rootViewController = self.window!.rootViewController as!
UINavigationController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let profileViewController = mainStoryboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
rootViewController.pushViewController(profileViewController, animated: true)
Ответ 5
func pushNewView() {
if let wind = UIApplication.sharedApplication().delegate?.window {
if let rootViewController = wind?.rootViewController {
let viewToPush = YourViewController()
let nav1 = UINavigationController(rootViewController: viewToPush)
if let alreadySomeOneThere = rootViewController.presentedViewController {
alreadySomeOneThere.presentViewController(nav1, animated: true, completion: nil)
}else {
rootViewController.presentViewController(nav1, animated: true, completion: nil)
}
}
}
}