Call a UIViewController with NavigationController programmatically in SWIFT 2.x - ios

I want to call a UIViewController with NavigationController designed in Storyboard programmatically when I select a dynamic shortcut.
I designed my UIViewController and its NavigationController in Main.storyboard and I put a storyboard ID (I called it MyUICtrlStoryID)
In order to create my dynamic shortcut I wrote the following code in the AppDelegate:
#available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) {
let handledShortCutItem = shortcutItem.type // handleShortCutItem(shortcutItem)
if handledShortCutItem == "3DTouchShourtcutID"{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
//FirstViewcontroller UI will be called as root UIView
let initialViewControlleripad : FirstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewControllerID") as! FirstViewController
initialViewControlleripad.go2MySecondUI = true //set this check variable in order to launch my second UI View from the first one.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = initialViewControlleripad
self.window?.makeKeyAndVisible()
}
}
in the viewWillAppear function of my FistViewController
if #available(iOS 9.0, *) {
let shortcutItem = UIApplicationShortcutItem(type: "3DTouchShortcutID",
localizedTitle: "This action",
localizedSubtitle: "action description",
icon: UIApplicationShortcutIcon(type: UIApplicationShortcutIconType.Add),
userInfo: nil)
UIApplication.sharedApplication().shortcutItems = [shortcutItem]
//check if FirstViewControler had to call the second UI
if go2MySecondUI == true {
self.go2MySecondUI = false
let newViewCtrl = self.storyboard?.instantiateViewControllerWithIdentifier("MyUICtrlStoryID") as? SecondViewController
// call second UI view
dispatch_async(dispatch_get_main_queue()) {
self.presentViewController(newViewCtrl!, animated: true, completion: nil)
}
// }
}
This code works fine: when I select, by 3d touch, my shortcut, my secondviewcontroller will be call and its UIView will be showed .. but without its navigation controller.
otherwise if I call my secondUIcontroller by a button designed in storyboard (with related segue callback) the secondUIView will be showed with navigation controller correctly..
What is wrong?

You need to embed your first view controller in a UINavigationController. So in the AppDelegate your code should be:
#available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) {
let handledShortCutItem = shortcutItem.type // handleShortCutItem(shortcutItem)
if handledShortCutItem == "3DTouchShourtcutID"{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
//FirstViewcontroller UI will be called as root UIView
let initialViewControlleripad : FirstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewControllerID") as! FirstViewController
initialViewControlleripad.go2MySecondUI = true //set this check variable in order to launch my second UI View from the first one.
let navigationController = UINavigationController(rootViewController: initialViewControlleripad)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
}
}
Then in viewWillAppear of the FirstViewController you need to push the second view controller rather than present. So your code should read:
if #available(iOS 9.0, *) {
let shortcutItem = UIApplicationShortcutItem(type: "3DTouchShortcutID",
localizedTitle: "This action",
localizedSubtitle: "action description",
icon: UIApplicationShortcutIcon(type: UIApplicationShortcutIconType.Add),
userInfo: nil)
UIApplication.sharedApplication().shortcutItems = [shortcutItem]
//check if FirstViewControler had to call the second UI
if go2MySecondUI == true {
self.go2MySecondUI = false
let newViewCtrl = self.storyboard?.instantiateViewControllerWithIdentifier("MyUICtrlStoryID") as? SecondViewController
// call second UI view
self.navigationController?.pushViewController(newViewCtrl, animated: true)
// }
}

Related

sideMenu not displayed after login

I have included kukushi side menu. I have done things according to the documentation. The screen shot with the codes in app delegate are below:
func setUpHomeVC() {
var window: UIWindow?
let storyBoard = UIStoryboard.init(name: "Dashboard", bundle: Bundle.main)
let contentViewController = storyBoard.instantiateViewController(withIdentifier: "DashboardViewController") as! DashboardViewController
let menuViewController = storyBoard.instantiateViewController(withIdentifier: "MenuViewCOntroller") as! MenuViewCOntroller
SideMenuController.preferences.basic.menuWidth = 240
SideMenuController.preferences.basic.statusBarBehavior = .hideOnMenu
SideMenuController.preferences.basic.position = .sideBySide
SideMenuController.preferences.basic.direction = .left
SideMenuController.preferences.basic.enablePanGesture = true
SideMenuController.preferences.basic.supportedOrientations = .portrait
SideMenuController.preferences.basic.shouldRespectLanguageDirection = true
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = SideMenuController(contentViewController: contentViewController,
menuViewController: menuViewController)
window?.makeKeyAndVisible()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setUpHomeVC()
return true
}
The identifier, class and module has been added according to the documentation. After login there is dashboard which consist of menu button. On login the code is:
private func goToDashboard() {
let dashboard = UIStoryboard(name: "Dashboard", bundle: nil)
let navView = dashboard.instantiateViewController(identifier: "DashboardViewController") as DashboardViewController
present(navView,animated: false)
}
On dashboard there is a button which have click event:
#IBAction func btnMenuClicked(_ sender: Any) {
print("Menu button has been clicked")
self.sideMenuController?.revealMenu(animated: true)
}
when I click on that button the print function is called but the menu is not revealed.
Can anyone explain it. Thanks in advance.
You can setup your appDelegate like this,
func setUpHomeVC() {
let storyboard = UIStoryboard(name: "Your Login Storyboard", bundle: nil)
let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginVC")
self.window?.rootViewController = initialViewController
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setUpHomeVC()
return true
}
And in your login event:
private func goToDashboard() {
self.pushVC()
}
private func pushVC() {
let storyBoard = UIStoryboard.init(name: "Dashboard", bundle: Bundle.main)
let contentViewController = storyBoard.instantiateViewController(withIdentifier: "DashboardViewController") as! DashboardViewController
let menuViewController = storyBoard.instantiateViewController(withIdentifier: "MenuViewCOntroller") as! MenuViewCOntroller
SideMenuController.preferences.basic.menuWidth = 240
SideMenuController.preferences.basic.statusBarBehavior = .hideOnMenu
SideMenuController.preferences.basic.position = .sideBySide
SideMenuController.preferences.basic.direction = .left
SideMenuController.preferences.basic.enablePanGesture = true
SideMenuController.preferences.basic.supportedOrientations = .portrait
SideMenuController.preferences.basic.shouldRespectLanguageDirection = true
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = SideMenuController(contentViewController: contentViewController,
menuViewController: menuViewController)
window?.makeKeyAndVisible()
}
Your DashboardVC should be in a navigation controller for sidemenu to present. Try pushing the controller instead of presenting it.If you have the controller in a different storyboard, you can use this function:
func pushVC(storyboardName : String, vcname : String) {
let vc = UIStoryboard.init(name: storyboardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcname)
self.navigationController?.pushViewController(vc, animated: true)
}
Also, I would suggest you learn about when to push, present, and make root view controllers as all serve different purposes.
I think your current implementation is wrong. The problem is we need to implement and push the view controllers as SideMenuControllers bundle, not separate ViewControlers
If you want to have the side menu after login, then set your login page first in your didFinishLaunchingWithOptions.
Then you can call setUpHomeVC from your loginVC.

How to go from appDelegate to viewController [duplicate]

This question already has answers here:
Storyboard - refer to ViewController in AppDelegate
(5 answers)
Closed 4 years ago.
if i have two viewControllers and i want when condition succeeded i want to go to another ViewController.
but i want to check every time the app launched so i stored the value on userDefaults and in appDelegate i checked for this value.
when i print the value i get it but i can not go to the desired controller.
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let active:Bool = defaults.bool(forKey: "activeBooking")
if active {
print("active \(active)")
let rootViewController = self.window!.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Final", bundle: nil)
let setViewController = mainStoryboard.instantiateViewController(withIdentifier: "finalBooking") as! BookingFromCurrentLocationVC
rootViewController?.navigationController?.popToViewController(setViewController, animated: false)
}
return true
}
i print the value in other controller and it return me true(my value) so why i can not go to another controller
You can try this:
In appDelegate and in didFinishLaunching
You can store this value in UserDefault and then check the condition:
if condition == true{
goToVC1()
}else{
goToVC2
}
func goToVC1() {
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let ObjVC1: ViewController = storyboard.instantiateViewController(withIdentifier: "VC1") as! VC1
let navigationController : UINavigationController = UINavigationController(rootViewController: ObjVC1)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
}
func goToVC2() {
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let ObjVC2: ViewController = storyboard.instantiateViewController(withIdentifier: "VC2") as! VC2
let navigationController : UINavigationController = UINavigationController(rootViewController: ObjVC2)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
}
Add a segue from Navigation controller to desired View Controller (with segue identifier "finalBookingVC") and replace the code inside your if condition with:
self.window?.rootViewController!.performSegue(withIdentifier: "finalBookingVC", sender: nil)
You can initiate your view controller in AppDelegate as below.
Perform your condition check and set the StoryboardID and ViewControllerID as per your requirement.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
//check your condition here and change the Storyboard name and ViewController ID as required
let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeVCID") as! HomeController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
return true
}
The first thing you need to check if an application is active and already open (top controller is finalBookingVC) then no need to do anything,
second thing finalBookingVC if already available in a stack then no need to push at that time you need to pop view controller.
If finalBookingVC is not available on the stack then you need to push this controller.
func gotoController() {
let navigationController : UINavigationController! = self.window!.rootViewController as! UINavigationController;
let arrViewController = navigationController;
if arrViewController != nil && !(arrViewController?.topViewController is finalBookingVC) {
var finalBookingVCFound:Bool = false;
for aViewController in (arrViewController?.viewControllers)! {
if aViewController is finalBookingVC {
finalBookingVCFound = true;
_ = navigationController?.popToViewController(aViewController, animated: true);
break;
}
}
if !finalBookingVCFound {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
let objVC:finalBookingVC = mainStoryboard.instantiateViewController(withIdentifier: "finalBookingVC") as! finalBookingVC;
navigationController?.pushViewController(objVC, animated: true);
}
}
}

Why status bar disappear when I tap push notification and move ViewController in swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
/* */
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = UIViewController()
self.window?.windowLevel = UIWindowLevelAlert + 1
self.window?.makeKeyAndVisible()
/*
fetch and add push notification data
*/
goAnotherVC()
}
func goAnotherVC() {
if (application.applicationState == UIApplicationState.active) {
/* active stage is working */
} else if (application.applicationState == UIApplicationState.inactive || application.applicationState == UIApplicationState.background) {
if (type == "1" || type == "2") {
let storyboard: UIStoryboard = UIStoryboard(name: "MyAppointments", bundle: nil)
let apptVC = storyboard.instantiateViewController(withIdentifier: "NotificationDetailViewController") as! NotificationDetailViewController
let navigationController = UINavigationController.init(rootViewController: apptVC)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
} else if (type == "3") {
let storyboard: UIStoryboard = UIStoryboard(name: "MyAppointments", bundle: nil)
let apptVC = storyboard.instantiateViewController(withIdentifier: "NotificationDetailViewController") as! NotificationDetailViewController
let navigationController = UINavigationController.init(rootViewController: apptVC)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
} else if (type == "4") {
let storyboard: UIStoryboard = UIStoryboard(name: "Enquiry", bundle: nil)
let enqVC = storyboard.instantiateViewController(withIdentifier: "EnquiryDetailViewController") as! EnquiryDetailViewController
let navigationController = UINavigationController.init(rootViewController: enqVC)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
}
}
}
Above code is fetch push notification data and send to related View Controller when user tapped on it. But I've found that status bar is missing when View Controller is open. Please let me know how to fix it, thanks.
At firs glance (and without actually verifying the code) my suspicion would be that the culprit is this:
self.window = UIWindow(frame: UIScreen.main.bounds)
You are setting your window to cover the full bounds of the view. To see if this is the issue, simply change that line to the following:
var rect = UIScreen.main.bounds
rect.origin.y += 20
self.window = UIWindow(frame: rect)
And see if the issue goes away. In my code, I've simply changed the top position of the window to allow for the status bar.

Value of type 'AppDelegate' has no member 'window'

Im trying to use the 3D touch Quick Actions and I'm setting it up copying VEA Software code. In his sample code it works perfectly but when I try to add it to my app I get some unusual errors. I am new to coding and swift so please explain as much as possible. Thanks. Below I have the code which is in my app delegate.
This is where I'm getting the error (self.window?):
#available(iOS 9.0, *)
func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) -> Bool
{
var handled = false
var window: UIWindow?
guard ShortcutIdentifier(fullType: shortcutItem.type) != nil else { return false }
guard let shortcutType = shortcutItem.type as String? else { return false }
switch (shortcutType)
{
case ShortcutIdentifier.First.type:
handled = true
var window = UIWindow?()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navVC = storyboard.instantiateViewControllerWithIdentifier("ProjectPage") as! UINavigationController
// Error on line below
self.window?.rootViewController?.presentViewController(navVC, animated: true, completion: nil)
break
case ShortcutIdentifier.Second.type:
handled = true
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navVC = storyboard.instantiateViewControllerWithIdentifier("ContactPageView") as! UINavigationController
// Error on line below
self.window?.rootViewController?.presentViewController(navVC, animated: true, completion: nil)
break
case ShortcutIdentifier.Third.type:
handled = true
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navVC = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! UINavigationController
// Error on line below
self.window?.rootViewController?.presentViewController(navVC, animated: true, completion: nil)
break
default:
break
}
return handled
}
Xcode 12.0 Swift 5.0
At the moment you need to:
Remove the “Application Scene Manifest” from info.plist file;
Remove scene delegate class;
Remove scene related methods in AppDelegate class;
If missing, add the property var window: UIWindow? to your AppDelegate class.
Add some logic in func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?).
Example of implementation when you need to support iOS 12 and 13:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
configureInitialViewController()
return true
}
private func configureInitialViewController() {
let initialViewController: UIViewController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
window = UIWindow()
if (condition) {
let mainViewController = storyboard.instantiateViewController(withIdentifier: "mainForm")
initialViewController = mainViewController
} else {
let loginViewController = storyboard.instantiateViewController(withIdentifier: "loginForm")
initialViewController = loginViewController
}
window?.rootViewController = initialViewController
window?.makeKeyAndVisible()
}
}
In iOS 13, Xcode 11, the sceneDelegate handles the functionality of UIScene and window. The window performs properly when used in the sceneDelegate.
When you are using Scene view then windows object is in the scene delegate. Copy window object and place it in the app delegate and it will work.
if your project already has SceneDelegate file ,then you need to use it insead of AppDelegate , like this way :
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = mainStoryBoard.instantiateViewController(withIdentifier: "setCountry")
window?.rootViewController = viewController
}
Sometimes when you have an issue in AppDelegate it can be solved with a quick Product -> Clean. Hope this helps.
This worked for me.
Add the following code inside SceneDelegate's first function's, func scene(...), if statement, if let windowScene = scene as? UIWindowScene {..Add Below Code Here..}.
Make sure to add import MediaPlayer at the top of the file.
let volumeView = MPVolumeView()
volumeView.alpha = 0.000001
window.addSubview(volumeView)
At the end your code should be:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
// MARK: Hide Volume HUD View
let volumeView = MPVolumeView()
volumeView.alpha = 0.000001
window.addSubview(volumeView)
}
}
first you need to specify which shortcut you need to use , cuz there are two types of shortcuts : dynamic and static and let say that you choose the static that can be done and added from the property list info then you have to handle the actions for each shortcut in the app delegate file in your project
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: #escaping (Bool) -> Void) {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let mainTabController = storyboard.instantiateViewController(withIdentifier: "Tab_Bar") as? Tab_Bar
let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginVC") as? LoginVC
let doctor = storyboard.instantiateViewController(withIdentifier: "DrTabController") as! DrTabController
getData(key: "token") { (token) in
getData(key: "type") { (type) in
if token != "" && type != "" , type == "2" {
self.window?.rootViewController = mainTabController
if #available(iOS 13.0, *) {
self.window?.overrideUserInterfaceStyle = .light
} else {
self.window?.makeKeyAndVisible()
}
if shortcutItem.type == "appointMent" {
mainTabController?.selectedIndex = 1
} else if shortcutItem.type == "Chatting" {
mainTabController?.selectedIndex = 2
}
} else if token != "" && type != "" , type == "1"{
self.window?.rootViewController = doctor
if #available(iOS 13.0, *) {
self.window?.overrideUserInterfaceStyle = .light
} else {
self.window?.makeKeyAndVisible()
}
if shortcutItem.type == "appointMent" {
mainTabController?.selectedIndex = 1
} else if shortcutItem.type == "Chatting" {
mainTabController?.selectedIndex = 2
}
} else if token == "" && type == "" {
self.window?.rootViewController = loginViewController
if #available(iOS 13.0, *) {
self.window?.overrideUserInterfaceStyle = .light
} else {
self.window?.makeKeyAndVisible()
}
if shortcutItem.type == "appointMent" {
mainTabController?.selectedIndex = 1
} else if shortcutItem.type == "Chatting" {
mainTabController?.selectedIndex = 2
}
}
}
}
}
this will be work so fine for you but first you have to determine the rootViewController we can say like :
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
self.window?.rootViewController = mainTabController
if #available(iOS 13.0, *) {
self.window?.overrideUserInterfaceStyle = .light
} else {
self.window?.makeKeyAndVisible()
}
if shortcutItem.type == "appointMent" {
mainTabController?.selectedIndex = 1
} else if shortcutItem.type == "Chatting" {
mainTabController?.selectedIndex = 2
}

Opening view controller from app delegate using swift

I am trying to create a push notification which determines which view to open according to information obtained from the push.
I have managed to get the information from the push, but I am now struggling to get the view to open
Looking at other stack overflow questions I have the following currently:
App Delegate Did finish loading:
//Extract the notification data
if let notificationPayload = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
// Get which page to open
let viewload = notificationPayload["view"] as? NSString
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
//Load correct view
if viewload == "circles" {
var viewController = self.window?.rootViewController?.storyboard?.instantiateViewControllerWithIdentifier("Circles") as! UIViewController
self.window?.rootViewController = viewController
}
}
Currently this is failing on the var ViewController = self... line.
You have to set ViewController StoryBoardId property as below image.
open viewController using coding as below in swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("Circles") as UIViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewControlleripad
self.window?.makeKeyAndVisible()
return true
}
For iOS 13+ (based on an article by dev2qa)
Open SceneDelegate.swift and add following
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// If this scene's self.window is nil then set a new UIWindow object to it.
self.window = self.window ?? UIWindow()
// Set this scene's window's background color.
self.window!.backgroundColor = UIColor.red
// Create a ViewController object and set it as the scene's window's root view controller.
self.window!.rootViewController = ViewController()
// Make this scene's window be visible.
self.window!.makeKeyAndVisible()
guard scene is UIWindowScene else { return }
}
There is an open-source navigation utility which attempts to make this easier. Example
Swift 3:
This is my preferred approach when presenting a new viewController from the current viewController through the AppDelegate. This way you don't have to completely tear down your view hierarchy when handling a push notification or universal link
if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "someController") as? SomeController {
if let window = self.window, let rootViewController = window.rootViewController {
var currentController = rootViewController
while let presentedController = currentController.presentedViewController {
currentController = presentedController
}
currentController.present(controller, animated: true, completion: nil)
}
}
Swift 3
To present the view together with the navigation controller:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier :"InboxViewController") as! InboxViewController
let navController = UINavigationController.init(rootViewController: viewController)
if let window = self.window, let rootViewController = window.rootViewController {
var currentController = rootViewController
while let presentedController = currentController.presentedViewController {
currentController = presentedController
}
currentController.present(navController, animated: true, completion: nil)
}
First Initialize the window
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
For setting rootViewController inside AppDelegate Class
let viewController = storyBoard.instantiateViewControllerWithIdentifier("Circles") as UIViewController
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
There is a swift 4 version
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewController(withIdentifier: "Circles") as UIViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewControlleripad
self.window?.makeKeyAndVisible()
return true}
In Swift 3
let mainStoryboard : UIStoryboard = UIStoryboard(name: StorybordName, bundle: nil)
let initialViewControlleripad : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: identifierName) as UIViewController
if let navigationController = self.window?.rootViewController as? UINavigationController
{
navigationController.pushViewController(initialViewControlleripad, animated: animation)
}
else
{
print("Navigation Controller not Found")
}
I'd say creating UIWindow each time you want to change rootViewController is bad idea. After couple changes of rootVC (using upper solution) you are gonna have many UIWindows in your app at one time.
In my opinion better solution is:
Get new rootVC: let rootVC = UIStoryboard(name: "StoryboardName", bundle: nil).instantiateViewControllerWithIdentifier("newRootVCIdentifier") as UIViewController
Set frame for new rootVC from UIScreen's bounds: rootVC.view.frame = UIScreen.mainScreen().bounds
Set new root controller for current window (here with animation): UIView.transitionWithView(self.window!, duration: 0.5, options: .TransitionCrossDissolve, animations: {
self.window!.rootViewController = rootVC
}, completion: nil)
Done!
You don't need method window?.makeKeyAndVisible(), cause this solution works on current app window.
Swift 3 SWRevealViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "LandVC") as! LandingPageVC
destinationViewController.webpageURL = NotificationAdvertisement._htmlpackagePath
destinationViewController.adID = NotificationAdvertisement._adID
destinationViewController.toneID = NotificationAdvertisement.toneID
let navigationController = self.window?.rootViewController as! UIViewController
navigationController.showDetailViewController(destinationViewController, sender: Any?.self)
SWIFT 4
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "LandVC") as! LandingPageVC
destinationViewController.webpageURL = NotificationAdvertisement._htmlpackagePath
destinationViewController.adID = NotificationAdvertisement._adID
destinationViewController.toneID = NotificationAdvertisement.toneID
let navigationController = self.window?.rootViewController as! UIViewController
navigationController.showDetailViewController(destinationViewController, sender: Any?.self)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(windowScene: windowScene)
let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController")
let rootNC = UINavigationController(rootViewController: vc)
self.window?.rootViewController = rootNC
self.window?.makeKeyAndVisible()
}

Resources