Swift - Accessing AppDelegate window from viewController - ios

I make walkthrough (onboarding flow) in my app and I'd like to have a skip button.
The button is located on viewController, so I figured out that the best way to move to another viewController would be access app delegate window.
However, it keeps getting me an error that AppDelegate.Type does not have a member called "window".
#IBAction func skipWalkthrough(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
AppDelegate.window!.rootViewController = RootViewController
}
Is there anything wrong with such approach?
Thanks in advance!

You have a typo it is supposed to be appDelegate not AppDelegate. So like this:
#IBAction func skipWalkthrough(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = RootViewController
}
Swift 3.2
#IBAction func skipWalkthrough(_ sender: AnyObject) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window!.rootViewController = controller
}

This is for with or without Storyboard and it is working for Swift 3+
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
appDelegate?.window?.rootViewController = homeController

Swift 3
This is a better way:
if let window = NSApplication.shared().windows.first {
window.acceptsMouseMovedEvents = true;
}

appDelegate.window!.rootViewController is not working in Swift 5
Here is working code
Add below extension
extension UIWindow {
static var key: UIWindow! {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
use
let mainSB = UIStoryboard(name: "Main", bundle: nil)
if let RootVc = mainSB.instantiateViewController(withIdentifier: "NavigationController") as? UINavigationController{
UIWindow.key.rootViewController = RootVc
}
UIWindow.key // to access only window

You can also use conditional binding to reach the window.
if let window = UIApplication.shared.windows.first {
// use window here.
}

You are using the protocol name (i.e. AppDelegate) instead of the instance:
Should be:
appDelegate.window!.rootViewController = RootViewController

You can access tab bar anywhere from the app. Use below:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController {
if let tabItems = tabBarController.tabBar.items {
let tabItem = tabItems[2]
tabItem.badgeValue = "5" //enter any value
}
}

This solution work for :
After Login / Register Programmatically add UITabbarController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = tabs
appDelegate.window!.makeKeyAndVisible()

Related

Swift return to preview UINavigationController

I have VC like a "Something went wrong". This VC i created like a separately VC(without storyboard) and i want to show it where i want. But in the "Something went wrong" View Controller i have a button "refresh". When a user click to this button he must to go back.
When i have some problem with parsing Json or something like this, i call Something went wrong" View Controller like this:
let navController = UINavigationController()
navController.pushViewController(SomethingWentWorngVC(nibName: "SomethingWentWorngView", bundle: nil), animated: false)
window?.rootViewController = navController
window?.makeKeyAndVisible()
also i have extension for getting window
extension UIViewController {
var appDelegate: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
var sceneDelegate: SceneDelegate? {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let delegate = windowScene.delegate as? SceneDelegate else { return nil }
return delegate
}
}
extension UIViewController {
var window: UIWindow? {
if #available(iOS 13, *) {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let delegate = windowScene.delegate as? SceneDelegate, let window = delegate.window else { return nil }
return window
}
guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else { return nil }
return window
}
}
in the SomethingWentWorngVC i have button for go to back
#IBAction func refreshAction(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: false)
}
but it doesnt work
in this alternate way you can use this , initially u need to create the common code in appdelegate using tag, then you need to do the addsubview to window for example,
for show
func showWentWrongScreen(){
let getVC = SomethingWentWorngVC
if let getWindow = self.window {
getVC.view.tag = 501
getVC.view.frame = getWindow.bounds
getWindow.addSubview(getVC.view)
}
}
for remove
func removeWentWrongScreen(){
if let getWindow = self.window, let getWentWrongView = getWindow.viewWithTag(501){
getWentWrongView.removeFromSuperview()
}
}
now you can use where u need

Swift. After addSubview click listeners dont work

I have a testVC. TestVC hasnt storyboard, this viewController has XIB file. I show this VC when i have no internet. And logic for a show this VC like this:
let getVC = NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil)
if let getWindow = self.window {
getVC.view.tag = 501
getVC.view.frame = getWindow.bounds
getWindow.addSubview(getVC.view)
}
also i have extension for UIViewController
extension UIViewController {
var appDelegate: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
var sceneDelegate: SceneDelegate? {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let delegate = windowScene.delegate as? SceneDelegate else { return nil }
return delegate
}
}
extension UIViewController {
var window: UIWindow? {
if #available(iOS 13, *) {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let delegate = windowScene.delegate as? SceneDelegate, let window = delegate.window else { return nil }
return window
}
guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else { return nil }
return window
}
}
all clicks in the TestVC works if i show this View Controller like this:
navController.pushViewController(NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil), animated: true)
but it doesn't suit me. I need to show NoInternetConnectionVC like i described above, that is, like this. When i show NoInternetConnectionVC like below all my listeners stop to work
let getVC = NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil)
if let getWindow = self.window {
getVC.view.tag = 501
getVC.view.frame = getWindow.bounds
getWindow.addSubview(getVC.view)
}
I tried to add line isUserInteractionEnabled to my code, like this
if let getWindow = self.window {
getVC.view.tag = 501
getVC.view.isUserInteractionEnabled = true //added line
getVC.view.frame = getWindow.bounds
getWindow.addSubview(getVC.view)
}
but it doesnt work
You have just added it as a subview. After adding subview move your controller to parent.
if let root = UIApplication.shared.windows.first?.rootViewController {
root.addChild(getVC)
getVC.didMove(toParent: root)
}

Dissmiss from UITabBarController

I guess it can be duplicated, but I looking everywhere and didn't find a solution for me.
So about my question. I have something like this
open this image to see more
In my AppDelegate I have func
func logIn() {
let userExist = UserDefaults.standard.string(forKey: "auth_key_user")
if userExist != nil && userExist != "" {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let whereToGo = storyboard.instantiateViewController(withIdentifier: "AllPostsOfUserTabBarController") as! AllPostsOfUserTabBarController
window?.rootViewController = whereToGo
}
}
If user exist it lead me to first view controller inside tab bar controller. There I have navigation button with action to logout.
I need log out(send data to the server) and then go to my first view controller with text field and button where I can again log in.
How do I need to implement it?
Try this code after logout-
DispatchQueue.main.sync() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginVC = storyboard.instantiateInitialViewController()
appDelegate.window?.rootViewController = loginVC
}
Hope it helps!
Put this code in function of your logout button. It will throw you back to your root controller.
func logoutBtnClicked()
{
DispatchQueue.main.sync()
{
(send your data to server)
self.navigationController?.popToRootViewController(animated: true)
}
}
Try this in appdelegate
While Login
self.window?.rootViewController = whereToGo
While Logout
func setupLoginViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginVC: UIViewController? = storyboard.instantiateViewController(withIdentifier: "loginVCID") as? UIViewController
let navController: UINavigationController? = UINavigationController(rootViewController: loginVC!) as UINavigationController
window?.rootViewController = navController
}

Back button disappears after creating AppDelegate in Swift 3.0

I created the structure as below in xcode 8 swift 3.0.
Before I add AppDelegate code. Back button still appear fine on Apply, Apply Behalf and Profile controller.
I use segue to open page.
But after I add AppDelegate code into Homepage and Login controllers , back button disappears on Apply, Apply behalf and profile controller page.
Can someone help or explain why is this happening ? How to enable back the back button on apply, apply behalf and profile page ?
Thanks.
Home.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var staffNumberLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
staffNumberLbl.text = UserDefaults.standard.object(forKey: "login") as? String
}
override func viewDidAppear(_ animated: Bool) {
let isUserLoggedIn = UserDefaults.standard.bool(forKey: "loggedIn")
if(!isUserLoggedIn){
self.performSegue(withIdentifier: "loginview", sender: self)
}
}
#IBAction func logoutData(_ sender: Any) {
UserDefaults.standard.set(false, forKey: "loggedIn")
UserDefaults.standard.synchronize();
let loginViewController = self.storyboard!.instantiateViewController(withIdentifier: "loginview") as! LoginViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = loginViewController
appDelegate.window?.makeKeyAndVisible()
}
}
Login.swift
import UIKit
class LoginViewController: UIViewController {
#IBOutlet var loginlbl: UITextField!
#IBOutlet var passlbl: UITextField!
#IBOutlet var login_button: UIButton!
var login: String!
var pw: String!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func loginData(_ sender: Any) {
login = loginLbl.text
pw = passLbl.text
if(login == "" || pw == ""){
return
}
else{
let url = URL(string: "http://localhost/login.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let LoginDataToPost = "login=\(login!)&pw=\(pw!)"
request.httpBody = LoginDataToPost.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil {
return
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async
{
let message = Int(json["message"]!)
let login = json["login"]
if(message == 1) {
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.set(login, forKey: "login")
UserDefaults.standard.synchronize();
self.dismiss(animated: true, completion: nil)
let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = myViewController
appDelegate.window?.makeKeyAndVisible()
print("Value for login is : \(login!)")
return
}
else {}
}
}
else {}
}
catch let jsonParse {}
}
})
task.resume()
}
}
}
AppDelegate.swift
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let isUserLoggedIn:Bool = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
if(!isUserLoggedIn) {
let loginViewController = mainStoryBoard.instantiateViewController(withIdentifier: "loginview") as! LoginViewController
window!.rootViewController = loginViewController
window!.makeKeyAndVisible()
}
else {
let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
window!.rootViewController = homePage
window!.makeKeyAndVisible()
}
return true
}
}
You are setting rootviewcontroller without embedding navigation controller to it in logoutData & loginData function.
Use this code :
let navigationController = UINavigationController.init(rootViewController: myViewController)
appDelegate.window?.rootViewController = navigationController
Use this code in AppDelegate:
if(!isUserLoggedIn) {
let loginViewController = mainStoryBoard.instantiateViewController(withIdentifier: "loginview") as! LoginViewController
let navigationController = UINavigationController.init(rootViewController: loginViewController)
appDelegate.window?.rootViewController = navigationController
window!.makeKeyAndVisible()
}
else {
let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let navigationController = UINavigationController.init(rootViewController: homePage)
appDelegate.window?.rootViewController = navigationController
window!.makeKeyAndVisible()
}
Remove this from Home.swift,
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = loginViewController
appDelegate.window?.makeKeyAndVisible()
because its not inheriting the properties of Navigation controller
and add it in Appdelegate.swift file
For the other 3 viewcontrollers, you need to add the Navigation controller between eachSegway in order to inherit it or code the button by instantiating the viewcontrollers respectively
After successful login,try to make NavigationController as rootViewController instead of your ViewController
Your back button will start appearing.
In AppDelegate, in else block, instead of this line
let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
write this
let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
Inside LoginViewController, in the block if(message == 1)
replace
let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController
with
let navController:UINavigationController = self.storyboard!.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
Also set storyboard identifier for UINavigationController in storyboard to NavigationController
Depending on your configuration:
self.navigationItem.hidesBackButton = YES;
OR:
self.navigationController.navigationItem.hidesBackButton = YES;
Or, if you just want to disable the button without hiding it, you can use this.
self.navigationController.navigationItem.backBarButtonItem.enabled = NO;

Traversing from AppDelegate to other controllers

The hierarchy i am using is something as follows ---
UIViewController->(present)->UINavigationController->(push)->UITableViewController.
How can I reach to 'UITableViewController' from my AppDelegate?
Add the following lines inside didFinishLaunchingWithOptions method in AppDelegate file
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var initialViewController = mainStoryboard.instantiateViewControllerWithIdentifier("myTable") as! UITableViewController //myTable is the storyboard id of your tableviewcontroller
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
I think you could firstly define a nil property in AppDelegate:
var referenceTableVC:UITableViewController?
Then in your UITableViewContoller, in the end of the method ViewDidload(), give the property the reference:
var targetDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
targetDelegate.referenceTableVC = self
I got the answer...
let window = UIApplication.sharedApplication().delegate?.window!!
if let rootVC = window!.rootViewController {
if let presentCont = rootVC.presentedViewController {
//presentCont can be any controller in my case it's 'UINavigationController' from navigation controller I can get all the controllers..
//navigationController.viewControllers
}
}

Resources