How create init VC from Storyboard? - ios

I have to create init VC from UIStoryboard in AppDelegate.
I used .instantiateInitialViewController() but I always get nil.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyBoard: UIStoryboard = .init(name: "Storyboard", bundle: nil)
if let vc = storyBoard.instantiateInitialViewController() {
window?.rootViewController = vc
window?.makeKeyAndVisible()
}
return true
}
My project:
I don't have 'ViewController' file (and class too). Why I always get 'nil' in vc? How it work? Please explain.

The most likely reason for storyBoard.instantiateInitialViewController to return nil is because your storyboard does not have an initial view controller. You can select a VC in the storyboard and check "Is Initial View Controller" to make it an initial view controller:
Note that if you set your storyboard as the "Main Interface" in your project settings, then the initial VC will show up automatically.
To avoid this, change this setting to an empty string:
Alternatively, you can give your VC an identifier in the identity inspector:
And use instantiateViewController(withIdentifier) instead
storyBoard.instantiateViewController(withIdentifier: "MyVC")

Try this..
let navigationController = self.window?.rootViewController as! UINavigationController
let storyboard = UIStoryboard(name: "Storyboard", bundle: nil)
let messageVC = storyboard.instantiateViewController(withIdentifier: "YourViewControllerID")
navigationController.pushViewController(messageVC, animated: true)

Try this. I'm always navigate between view controllers with these codes ,
let vc = storyboard?.instantiateViewController(withIdentifier: "ViewControllerStoryBoardId") as! YourViewControllerClass
vc.page_idenifier = "Home page"//eg:- Passing data
navigationController?.pushViewController(vc, animated: true)

Related

set root view controller in main storyboard

so i have this storyboard and i want the user to be shown the login view controller if he is not logged in or the tab view controller otherwise.
this is my code inside the app delegate :
`
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
UITabBar.appearance().tintColor = .white
// check user
let authListener = Auth.auth().addStateDidChangeListener { auth, user in
if user != nil {
print("USER IS NOT NIL")
userService.observeUserProfile(uid: user!.uid) { userProfile in
userService.currentUserProfile = userProfile
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TabBarVC") as! UITabBarController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
} else {
print("USER IS NIL")
userService.currentUserProfile = nil
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "FirstVC") as! UIViewController
vc.modalPresentationStyle = .fullScreen
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
}
}
`
My problem is that if the user is not logged it looks like this:
As you can see the view is not full screen even though i specified that in the app delegate so the user can simply dismiss it and enter the main screen. Also in the tab view controller i have the main screen with a playing video and the login screen also has a playing video in the background and both videos are played at the same time XD .Any tips would be welcome.
change storyboard--> viewcontroller---> attribute inspector---> change presentation from Automatic to Full Screen
let nav = UINavigationController()
nav.navigationBar.isHidden = true
//your Controller
let first = Router.shared.splashVC()
let third = Router.shared.CustomTabbarVC()
third.selectedIndex = 0
//add multiple controller in array
nav.viewControllers = [first,third]
UIApplication.shared.keyWindow?.rootViewController = nav
UIApplication.shared.keyWindow?.makeKeyAndVisible()
First Select all ViewController and change presentation mode Automatic from Full Screen in Simulated Metrics.
Added UINavigationController in rootViewController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TabBarVC") as! UITabBarController
let navigationController = UINavigationController(rootViewController: vc)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = navigationController
vc.navigationController?.isNavigationBarHidden = true
self.window?.makeKeyAndVisible()

Storyboard's view controller not showing up when programmatically set as root view controller

I am trying to change the rootVC based on some condition on the app launch. All of my VCs are made in the storyboard so I am doing it like this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
checkPhotoLibraryAccess()
return true
}
func checkPhotoLibraryAccess(){
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.denied || PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.notDetermined {
showPermissionVC()
} else {
showContainerVC()
}
}
func showPermissionVC (){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootVC = storyboard.instantiateViewController(withIdentifier: "askPermissionVC")
UIApplication.shared.windows.first?.rootViewController = rootVC
self.window?.makeKeyAndVisible()
}
func showContainerVC (){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootVC = storyboard.instantiateViewController(withIdentifier: "containerVC")
UIApplication.shared.windows.first?.rootViewController = rootVC
self.window?.makeKeyAndVisible()
}
I have removed the arrow showing the initial VC from the storyboard so that it won't have a conflict with the code. However, I got this error and nothing showed up on screen in simulator:
[Application] Failed to instantiate the default view controller for
UIMainStoryboardFile 'Main' - perhaps the designated entry point is
not set?
I have now removed the "Main storyboard file base name" property from info.plist. This time the error is gone but still nothing is showing up. What am I doing wrong?
You need to initialize the window programmatically.
Try adding the following to the beginning of your didFinishLaunchingWithOptions method in Appdelegate
self.window = UIWindow()
Also in your showPermissionVC and showContainerVC methods, replace this line:
UIApplication.shared.windows.first?.rootViewController = rootVC
with:
window?.rootViewController = rootVC

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);
}
}
}

Load A View Controller programmatically from a UIView

I am using the following from within a class to call a UIViewController. The UIViewController loads, but then becomes unresponsive after loading.
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeC = storyboard.instantiateViewController(withIdentifier:
"ViewJoeProfileController") as? ViewJoeProfileController
if homeC != nil {
homeC!.view.frame = (self.window!.frame)
self.window!.addSubview(homeC!.view)
self.window!.bringSubview(toFront: homeC!.view)
}
}
Any suggestions to make the UIViewController being loaded responsive would really help!
If you specifically want to add to the window, you should do it the proper way and add the whole ViewController:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
guard let window = UIWindow(frame: UIScreen.mainScreen().bounds) else { return true }
if let homeC = storyboard.instantiateViewController(withIdentifier: "ViewJoeProfileController") as? ViewJoeProfileController {
window.rootViewController = mainViewController
window.makeKeyAndVisible()
}
return true
}
But honestly that structure still doesn't seem correct. Why are you adding a view to the window, instead of using an initial view controller and then adding to itsviews, or segueing to different ViewControllers?.
Try using this I need to make root View Controller
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "ViewJoeProfileController") as! ViewJoeProfileController
let nav = UINavigationController(rootViewController: vc)
nav.isNavigationBarHidden = true
self.window?.rootViewController=nav
self.window?.makeKeyAndVisible()

Display a particular viewcontroller in Xcode/swift using if else conditional statements

I want a to have a conditional if statement to be run immediately when the app is open. Basically, it will be
if x = true {
//segue to viewcontroller1
} else {
//stay on this page
}
This will be in Xcode and coded in swift (obviously the syntax is wrong)... what is the appropriate way to write the syntax to segue to a particular view controller if the condition is true and stay on the one that normally is opened up to upon opening the app? Also, where do I put this? I considered the viewdidload method in the, normally, first displayed viewcontroller, but the variable needs to be checked before the view loads, such that the view changes to a different one if the condition is true and that one opens first instead?
Edit: I tried to set the code in the AppDelegate.swift as follows:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if x{
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let ViewController = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = ViewController
} else{
//same code as above but to different VC
}
return true
}
But when I run this I get an error in the appDelegate saying that "libc++abi.dylib: terminating with uncaught exception of type NSException". What is the right way to modify this code?
If you want to select the scene before presenting. You can add the following in appDelegate.swift, in application(application: UIApplication, didFinishLaunchingWithOptions):
var id = x ? "id1" : "id2"
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let exampleVC: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: id) as UIViewController
self.window?.rootViewController = exampleVC
self.window?.makeKeyAndVisible()
Make sure you name the scenes in storyboard
If you OK with the first scene showing and then choosing to segue:
if x {
self.performSegue(withIdentifier: "id1", sender: self)
} else {
self.performSegue(withIdentifier: "id2", sender: self)
}
Again, make sure to name the segues in storyboard
Another option, use UINavigationController. Set a Navigation Controller as your root view controller
let id = x ? "id1" : "id2"
let mainStoryboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
let exampleVC = mainStoryboard.instantiateViewController(withIdentifier: id) as UIViewController
let navigationController = UINavigationController(rootViewController: exampleVC)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()

Resources