Back when current view controller is not presented by segue. Swift - swift

I am trying to present VC2 from VC1 without using segue. It works. Then, I tried to use self.navigationController?.popViewControllerAnimated(true) to back but it does not work. I am wondering what is the code I should use to back from VC2 to VC1. Below code is in appDelegate.
AppDelegate
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC2 = storyboard.instantiateViewControllerWithIdentifier("VC2") as! VC2
let navController = UINavigationController(rootViewController: VC2)
self.topViewController()!.presentViewController(navController, animated: false, completion: nil)
func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let MMDrawers = base as? MMDrawerController {
for MMDrawer in MMDrawers.childViewControllers {
return topViewController(MMDrawer)
}
}
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
VC2
#IBAction func backButtonTapped(sender: AnyObject) {
print(self.navigationController?.viewControllers) // print([<MyAppName.VC2: 0x12f147200>])
self.navigationController?.popViewControllerAnimated(true)
}

Here is the Flow of your navigation :
Current Screen - Presenting A New Screen (Which itself embed within a navigation controller with vc2) so Popviewcontroller won't work .
If you present any viewcontroller then popviewcontroller wont work rather use dismissviewcontroller to come out previous screen .
Use This :
self.dismissViewControllerAnimated(true, completion: {})
Solved!
Thanks.

Related

NavigationController PushViewController does not show

I am trying to navigate to the ClassroomViewController once I receive the push notification. I have put a break point, and it hits all the lines, but it does not show the ClassroomViewController. I am wondering what I am missing in my current implementation.
I added identifier on the ClassroomViewController on storyboard.
AppDelegate
public var keyWindow: UIWindow? {
return UIApplication.shared.windows.first { $0.isKeyWindow }
}
Helper Method which does not work. I am wondering why the following approach does not work.
private func notificationToNavigate() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let topViewController = appDelegate.keyWindow?.rootViewController
else { return }
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let cVC = storyboard.instantiateViewController(withIdentifier:"ClassroomViewController") as! ClassroomViewController
topViewController.navigationController?.pushViewController(cVC, animated: true)
}
Helper Method which works
private func notificationToNavigate() {
guard let window = UIApplication.shared.keyWindow else { return }
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let cVC = storyboard.instantiateViewController(withIdentifier:"ClassroomViewController") as! ClassroomViewController
window.rootViewController = UINavigationController(rootViewController: cVC)
window.makeKeyAndVisible()
}
If topViewController is indeed the key window's root view controller, then it cannot have a navigation controller; if pushing is possible at all, then it must be a navigation controller. So you would say
(topViewController as? navigationController)?.pushViewController...
On the other hand, if topViewController is not a navigation controller (so that the above fails), then pushing is simply impossible and you need to think of something else to do.

Swift: pass data to first child of NavigationController instantiate with storyboardID

I want to pass data to the first viewController which is embeded in navigationController.
To access this navigation controller it has a storyBoardID, I arrive at instantiate navigationController but I can not pass him data,
Here is my code:
extension UINavigationController {
func dismissAndPresentNavigationController(from storyboard: UIStoryboard?, identifier: String) {
guard let navigationController = storyboard?.instantiateViewController(withIdentifier: identifier) as? UINavigationController else { return }
print("OK")
if let nav = navigationController.navigationController?.viewControllers.first as? ChatBotViewController{
print("OK2")
}
self.dismiss(animated: false, completion: nil)
self.present(navigationController, animated: true, completion: nil)
}
}
The identifier that I put in parameter is the storyBoardID of the navigation controller.
How to transmit data to the first controller of navigationcontroller?
SOLUTION:
extension UINavigationController {
func dismissAndPresentNavigationController(from storyboard: UIStoryboard?, identifier: String, with fittoBottle: FittoBottle) {
guard let navigationController = storyboard?.instantiateViewController(withIdentifier: identifier) as? UINavigationController else { return }
if let nav = navigationController.viewControllers.first as? ChatBotViewController{
nav.fittoBottle = fittoBottle
}
self.dismiss(animated: false, completion: nil)
self.present(navigationController, animated: true, completion: nil)
}
After instantiating the navigation controller from the storyboard, you will be able to access the root view controller via navigationController.viewControllers.first.
guard let navigationController = storyboard?.instantiateViewController(withIdentifier: identifier) as? UINavigationController else { return }
if let chatBotViewController = navigationController.viewControllers.first as? ChatBotViewController {
chatBotViewController.fittoBottle = fittoBottle
}
self.dismiss(animated: false, completion: nil)
self.present(navigationController, animated: true, completion: nil)
To communicate between view controllers in an iOS app, the best way is using protocol (delegate) or Notification. In you case, extending an UINavigationController doesn't sound a good idea, because you shouldn't relay on extension methods to instance view controller and then passing any data to it, and as an extension method, it's not the responsibility for an UINavigationController to take care about ChatBotViewController or any other instanced controllers.
For my suggestion, in anywhere you want to show the ChatBotViewController, in your storyboard, create a presenting modal segue to the ChatBotViewController (which is embedded in an UINavigationController), and use performSegue(withIdentifier:sender:) to initiate the navigation controller, and override prepare(for:sender:) to set the data you want to pass in your ChatBotViewController.
Here's some codes for explaining:
import UIKit
struct FittoBottle {
}
class ChatBotViewController: UIViewController {
var fittoBottle = FittoBottle()
}
class ViewController: UIViewController {
func showChatController() {
/*
If there is any controller is presented by this view controller
or one of its ancestors in the view controller hierarchy,
we will dismiss it first.
*/
if presentedViewController != nil {
dismiss(animated: true) {
self.showChatController()
}
return
}
// Data that will be sent to the new controller
let fittoBottle = FittoBottle()
// ChatBotViewControllerSegue is the segue identifier set in your storyboard.
performSegue(withIdentifier: "ChatBotViewControllerSegue", sender: fittoBottle)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let navigationController = segue.destination as? UINavigationController else {
return
}
guard let chatBotController = navigationController.viewControllers.first as? ChatBotViewController else {
return
}
// Get the data from sender, if not found, create it there.
// Or if you don't pass it through sender, you can specify it here.
let fittoBottle = sender as? FittoBottle ?? FittoBottle()
chatBotController.fittoBottle = fittoBottle
}
}

Change ViewController from Tabbar

I have a UITabBarController with 3 tabs and a SettingsVC where you can choose the appearance of MainVC (There are 2 different ViewControllers which based on what user prefers should be shown as the MainVC).
I made the application and it works but it's really buggy, cause I was just pushing the ViewControllers on top of each other, and in some certain conditions you see bugs while switching tabs.
Main.storyboard
Here is some part of my code(after trying a lot of stuff) which changes the VC's based on UserDefaults
CheckSettingsStatus.swift
//
// Check for Double Column Settings and navigate to Double Column VC
//
func checkMainVCViewStatusAndNavigateAcordingly(){
if UserDefaults.standard.integer(forKey: KEY_MAIN_VC_VIEW) == 1{
//let appDel = UIApplication.shared.delegate as! AppDelegate
//appDel.goToDoubleMainVC()
let mainVC = storyboard?.instantiateViewController(withIdentifier: "DoubleColumnMainVC") as! DoubleColumnMainVC
self.navigationController?.viewControllers[0] = mainVC
//navigationController?.pushViewController(mainVC, animated: false)
var navigationArray = self.navigationController?.viewControllers
print("Number of VCs = \(String(describing: navigationArray?.count))")
if navigationArray?.count == nil{
self.navigationController?.pushViewController(mainVC, animated: false)
}else{
self.navigationController?.popToRootViewController(animated: false)
}
// self.navigationController?.viewControllers = navigationArray!
}
}
//
// same as function above but goes to MainVC
//
func checkDoubleColumnMainVCViewStatusAndNavigateAcordingly(){
if UserDefaults.standard.integer(forKey: KEY_MAIN_VC_VIEW) == 0{
// let appDel = UIApplication.shared.delegate as! AppDelegate
// appDel.goToMainVC()
let mainVC = storyboard?.instantiateViewController(withIdentifier: "MainVC") as! MainVC
self.navigationController?.viewControllers[0] = mainVC
var navigationArray = self.navigationController?.viewControllers
print("Number of VCs = \(String(describing: navigationArray?.count))")
if navigationArray?.count == nil{
navigationController?.pushViewController(mainVC, animated: false)
}else{
self.navigationController?.popToRootViewController(animated: false)
}
// self.navigationController?.viewControllers = navigationArray!
}
}
With this in ViewWillAppear of both this Controllers I call these functions to switch accordingly.
Any ideas what I'm doing wrong? Can I push controllers from UITabBarController and not NavigationController? something like:
tabBarController.pushViewController(mainVC, animated: false)
instead of:
navigationController.pushViewController(mainVC, animated: false)
Thank you in advance
UPDATE:
In my best case when everything works nicely, on first launch of the app (to the second mainVC) the Buttons in NavBar doesn't work.
EDIT:
I just realised that the NavigationBar that I'm seeing above my SecondMainVC is the NavigationBar from MainVC, that is why the buttons are not working. how is that possible?
I faced same issue while trying to develop a tab bar controller in storyboard , for this reason I found that the best way is to implement it by code.
so you can make your code look like this :
1) create a a sub class of UITabController and let it conform to UITabBarControllerDelegate
class TabBarVC: UITabBarController , UITabBarControllerDelegate {
2)then write this method in your class to initialize the tabs in your project:
private func settingUpTabBarAndInitializingViewControllers(){
//self delagting
self.delegate = self
//home tab
let homeStoryboard = UIStoryboard(name: Constants.StoryBoards.homeStoryboard, bundle: nil)
let homeVC = homeStoryboard.instantiateViewController(withIdentifier: Constants.ControllersIDs.homeScreen) as! HomeVC
// shop tab
let shopStoybaord = UIStoryboard(name: Constants.StoryBoards.shopStoryboard, bundle: nil)
let shopVC = shopStoybaord.instantiateViewController(withIdentifier: Constants.ControllersIDs.shopScreen) as! ShopVC
//offers tab
let offersStoryboard = UIStoryboard(name: Constants.StoryBoards.offersStoryboard, bundle: nil)
let offersVC = offersStoryboard.instantiateViewController(withIdentifier: Constants.ControllersIDs.offersScreen) as! OffersVC
//more tab
let moreStoryboard = UIStoryboard(name: Constants.StoryBoards.MoreScreenStoryboard, bundle: nil)
let moreVC = moreStoryboard.instantiateViewController(withIdentifier: Constants.ControllersIDs.moreVCScreen) as! MoreOptionsTVC
//setting VCs
self.viewControllers = [homeVC , shopVC , offersVC , moreVC]
//setting buttons
//buttons images
let homeImage = UIImage(named: "TabHome")
let shopImage = UIImage(named : "TabShop")
let offerImage = UIImage(named: "TabOffers")
let moreImage = UIImage(named: "TabMenu")
// buttons shakhsiyan
let homeButton = UITabBarItem(title: homeText, image: homeImage, selectedImage: homeTappedImage)
let shopButton = UITabBarItem(title: shopText, image: shopImage, selectedImage: shopTappedImage)
let offersButton = UITabBarItem(title: offersText, image: offerImage, selectedImage: offersTappedImage)
let moreButton = UITabBarItem(title: moreText, image: moreImage, selectedImage: moreTappedImage)
homeVC.tabBarItem = homeButton
shopVC.tabBarItem = shopButton
offersVC.tabBarItem = offersButton
moreVC.tabBarItem = moreButton
}
P.S. you can add tabs as much as you want and while scrolling in them you wont face any bug,
make sure to have only one navigation controller before your tab bar controller.
Check this hope it helps
Ok you can create a DEMO to see how thing works.After that you can implement it in your project.I know it may not look good to you but read it once and see image attached i am sure will get your answer.
1.I have created two UIViewControllers with the UITabBarController.
2.I have created class ItemFirstVC,ItemTwoVC and assigned to UIViewControllers in storyboard
3.Each controller is embedded in UINavigationController
4.Create a custom class of UITabBarController
5.Assign it to UITabBarController in storyboard
6.Now Each UIViewController has a button named as Firs Button,Second Button
7.From each button i have connected Action Segue to one more controller as you can see in image.
8.Now i have created a third UIViewController which is separate from UITabBarController.
9.Now we will load that Third UIViewController in UITabBarController
10.Create one more class ItemThirdVC and assign it to third UIViewController.
11.It also has a button named as third button action segued to one more UIViewController
12.Now switch to custom class of UITabBarContoller
// variable required to see work in action
var count = 0
class CustomTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// remember to assign delegate
delegate = self
}
// this delegate indicates whether this tab should be selected or not
extension CustomTabBarController : UITabBarControllerDelegate{
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
// switch to UIViewController tabs multiple times
count = count + 1
if(count == 5){
// when count reaches 5 a new controller will load
let navigationController = viewController as? UINavigationController
guard navigationController != nil else {return true}
let viewController = storyboard?.instantiateViewController(withIdentifier: "ItemThreeVC")
guard let vc = viewController else {return true}
navigationController?.setViewControllers([vc], animated: false)
}
return true
}
}

presentViewController has no navigationController swift

My transition to the next view is like this:
if let navigationController = navigationController {
if let storyboard:UIStoryboard = UIStoryboard(name: "myStoryboard", bundle: nil) {
if let vc = storyboard.instantiateViewControllerWithIdentifier("myViewController") as? MyViewController {
dispatch_async(dispatch_get_main_queue()) {
navigationController.presentViewController(vc, animated: true, completion: nil)
}
}
}
}
This works fine. I want this kind of transition. But when I call following code in MyViewController, the NavigationController is nil:
if let navigationController = navigationController {
print("yeah i have a nc")
} else {
print("its nil") //this will call
}
When I use navigationController.pushViewController(vc, animated: true)
everything works fine. But I really want the transition. Is this a wrong implementation on my side or is presentViewController always without a navigationController? If yes, what can I do?
My Controller A is already embedded in a navigationController. I use navigationController.presentViewController to go to MyViewController. And from MyViewController I want to push to a next ViewController C.
SOLUTION THAT WORKED FOR ME
I don't know why, but when you use the presentViewController you have to define a new(?) root for your navigationController.
In this context I understood Ahmad Fs answer.
if let storyboard:UIStoryboard = UIStoryboard(name: "myStoryboard", bundle: nil) {
if let vc = storyboard.instantiateViewControllerWithIdentifier("MyViewController") as? MyViewController {
if let navController:UINavigationController = UINavigationController(rootViewController: vc) {
dispatch_async(dispatch_get_main_queue()) {
self.presentViewController(navController, animated:true, completion: nil)
}
}
}
}
SWIFT 3
let storyboard = UIStoryboard(name: UIConstants.Storyboards.registration, bundle: nil)
if let vc = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as? YourViewController {
let navigationController = UINavigationController(rootViewController: vc)
DispatchQueue.main.async {
navigationController.present(vc, animated: true)
}
}
I found "my" solution here

How do I find the visibleViewController in appdelegate?

I currently instantiate the storyboards programmatically like so:
var iphone35StoryBoard:UIStoryboard = UIStoryboard(name: "iphone35", bundle: nil)
var initialViewController:UIViewController = iphone35StoryBoard.instantiateInitialViewController() as! UIViewController
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
This is my first time working with push notifications, so I'm unsure as the best practice, but what i'm trying to do is in didReceiveRemoteNotification and while the app is in an active state(foreground), I would like to be able to determine what view the user is currently on to determine if i should A) Call a local notificaiton or B) update the view if the push notification corresponds to the visible view.
Using various other SO related questions, I have tried to access the visibleviewcontroller using these variations of code:
let navigationController = application.windows[0].rootViewController as! UINavigationController
1)
let visibleController: AnyObject? = navigationController.visibleViewController
if visibleController is ProfileViewController {
println("this works")
}
and
2)
let viewControllers: [UIViewController] = navigationController.viewControllers as! [UIViewController]
for vc in viewControllers {
if vc is ProfileViewController {
println("this works")
}
}
3)
if let wd = self.window {
var vc = wd.rootViewController
if(vc is UINavigationController){
vc = (vc as UINavigationController).visibleViewController
}
if(vc is ProfileViewController){
println("this works")
}
}
the problem i'm running into is that I can only obtain the rootviewcontroller and never the visible view controller. The rootviewcontroller in this case is a login screen, and despite me being on the profileViewController, i can only obtain the loginviewcontroller. Is this the best method for dealing with push notifications?
Move to destination view controller from storyboard when push notification will came
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
var destViewController : destVC
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("destVC") as! destVC
var navigationController = UIApplication.sharedApplication().keyWindow!.rootViewController as! UINavigationController
navigationController.pushViewController(destViewController, animated: true)
This is working for me from appdelegate.
Use notification center for more stuff :
NSNotificationCenter.defaultCenter().postNotificationName("name", object: nil, userInfo:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "method:", name: "name", object: nil)
func method(notification: NSNotification) {
//Do your stuff.
}
Passing data with notification center
NSNotificationCenter.defaultCenter().postNotificationName("name", object:nil, userInfo:["message":"Unable to add \(homeName) Home"])
func method(notification: NSNotification) {
//Do your stuff.
println(notification.userInfo)
}