Search code examples
iosswift3xcode8appdelegateback-button

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.

enter image description here

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

Solution

  • 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()
    }