Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How sign in automatically without asking login in iOS Swift?

I have different story board called Main, tabBar, home, map, etc. In tabBar storybard, I have used SWRevealViewController view and initiated as initially view. In main Storyboard only two are used namely sign in and sign up controller.

Here is my screenshot of tabBar storyBoard enter image description here

My question is when user logout and come back it automatically goes to home screen instead of going to sign in screen [This issue is due to SWRevealViewController is initial view controller].

Here code i tried : In sign view controller

In viewDidAppear check user available in firebase or not

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if API.User.CURRENT_USER != nil {
        // segue to the Tab Bar Controller
        self.performSegue(withIdentifier: "signInToTabBar", sender: nil)

    }
}

Sign in action:

  @IBAction func SignInButton(_ sender: Any) {

    view.endEditing(true)

    guard
        let email = emailTextField.text, !email.isEmpty,
        let password = passwordTextField.text, !password.isEmpty
        else {

            self.showErrorAlert(message: "Username or email or passowrd should not be empty")
            return
    }
    // show the progress to the user
    ProgressHUD.show("Starting sign-in...", interaction: false)

    // use the signIn class method of the AuthService class
    AuthService.signIn(email: emailTextField.text!, password: passwordTextField.text!, onSuccess: {
        // on success segue to the Tab Bar Controller
        API.User.observeCurrentUser { user in

            guard let currentUser = Auth.auth().currentUser else {
                return
            }

            PrefsManager.sharedinstance.UIDfirebase = currentUser.uid
            PrefsManager.sharedinstance.username  = user.username!
            PrefsManager.sharedinstance.userEmail = user.email!
            PrefsManager.sharedinstance.imageURL  = user.profileImageURL!

            ProgressHUD.showSuccess("Sucessfully signed in.")
            self.performSegue(withIdentifier: "signInToTabBar", sender: nil)

        }

    }, onError: { errorString in
        ProgressHUD.dismiss()
        self.showErrorAlert(message: errorString ?? "Server error")
    })

}

}

SWRevealViewController menu table i am listing menu like home, bookings, profile, logout :

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{


    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MenuTableViewCell

    cell.menuName.text = menuName[indexPath.row]
    cell.menuIcon.image = UIImage(named: menuImage[indexPath.row])


    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

  //        tableView.deselectRow(at: indexPath, animated: true)

    let row = indexPath.row

    if row == 0{

        let storyboard = UIStoryboard(name: "Home", bundle: nil)

        let obj = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
        let navController = UINavigationController(rootViewController: obj)
        navController.setViewControllers([obj], animated:true)
        navController.tabBarController?.tabBar.isHidden = false
        self.revealViewController().setFront(navController, animated: true)
        self.revealViewController().setFrontViewPosition(FrontViewPosition.left, animated: true)

    } else if row == 1{

        let storyboard = UIStoryboard(name: "Bookings", bundle: nil)
        let obj = storyboard.instantiateViewController(withIdentifier: "BookingsViewController") as! BookingsViewController
        let navController = UINavigationController(rootViewController: obj)
        navController.setViewControllers([obj], animated:true)
        self.revealViewController().setFront(navController, animated: true)
        self.revealViewController().setFrontViewPosition(FrontViewPosition.left, animated: true)


    } else if row == 2 {

        let storyboard = UIStoryboard(name: "Profile", bundle: nil)
        let obj = storyboard.instantiateViewController(withIdentifier: "profileViewController") as! profileViewController
        let navController = UINavigationController(rootViewController: obj)
        navController.setViewControllers([obj], animated:true)
        self.revealViewController().setFront(navController, animated: true)
        self.revealViewController().setFrontViewPosition(FrontViewPosition.left, animated: true)

    } else if row == 3 {
        print(indexPath)
        // Log out user from Firebase
        AuthService.signOut(onSuccess: {
            // Present the Sign In VC
    //                PrefsManager.sharedinstance.logoutprefences()
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let signInVC = storyboard.instantiateViewController(withIdentifier: "signInViewController")
                        self.present(signInVC, animated: true)

  //                self.navigationController?.pushViewController(signInVC, animated: true)

        }) { (errorMessage) in

            ProgressHUD.showError(errorMessage)

        }



    }


}

IN home view controller, checking user available or not:

  override func viewDidAppear(_ animated: Bool) {

    if API.User.CURRENT_USER != nil {
        // segue to the Tab Bar Controller
        self.performSegue(withIdentifier: "signInToTabBar", sender: nil)

    }

    super.viewDidAppear(true)
    self.tabBarController?.tabBar.isHidden = false

}

like image 795
PvDev Avatar asked Jul 27 '18 05:07

PvDev


1 Answers

When you signout from the app, you have to set your signIn view controller as the root view controller like this.

AuthService.signOut(onSuccess: {
       // Present the Sign In VC
       let storyboard = UIStoryboard(name: "Main", bundle: nil)
       let signInVC = storyboard.instantiateViewController(withIdentifier: "signInViewController") as! signInViewController
       let nav = UINavigationController(rootViewController:signInVC)
       let application = UIApplication.shared.delegate as! AppDelegate
       application.window!.rootViewController = nav

}) { (errorMessage) in
        ProgressHUD.showError(errorMessage)
 }

Now in AppDelegate.swift file, in application(_:didFinishLaunchingWithOptions:) method, you have to check that user is nil or not.

if API.User.CURRENT_USER != nil {
       let mainNav = self.window?.rootViewController as! UINavigationController
       let storyBoard = UIStoryboard(name: "tabBar", bundle:nil)
       let sWRevealViewController = storyBoard.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
       mainNav.pushViewController(sWRevealViewController, animated: false)
 }

NOTE: Please add your storyboard Id and View controller name in identifier name and view controller name.

like image 51
Khushbu Avatar answered Nov 12 '22 14:11

Khushbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!