热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

iOSSwift中如何实现自动登录?

本文介绍了在iOSSwift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。

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.

我有不同的故事板叫做Main,tabBar,home,map等。在tabBar的故事栏中,我使用了SWRevealViewController视图并作为初始视图启动。在主要的Storyboard中只使用了两个即登录和注册控制器。

Here is my screenshot of tabBar storyBoard enter image description here

这是tabBar storyBoard的截图

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].

我的问题是当用户注销并返回时它自动进入主屏幕而不是登录屏幕[此问题是由于SWRevealViewController是初始视图控制器]。

Here code i tried : In sign view controller

我试过这里的代码:在符号视图控制器中

In viewDidAppear check user available in firebase or not

在viewDidAppear中检查firebase中是否有可用的用户

  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 :

SWRevealViewController菜单表我列出了菜单,如家,预订,个人资料,注销:

    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

}

2 个解决方案

#1


3  

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

当您从应用程序注销时,您必须将signIn视图控制器设置为这样的根视图控制器。

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.

现在在AppDelegate.swift文件中,在application(_:didFinishLaunchingWithOptions :)方法中,你必须检查用户是否为nil。

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.

注意:请在标识符名称和视图控制器名称中添加故事板ID和视图控制器名称。

#2


0  

Instead of navigation(performSegue), you have to change your RootViewController and set signInViewController as root VC.

您必须更改RootViewController并将signInViewController设置为root VC,而不是导航(performSegue)。

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let obj = storyboard.instantiateViewController(withIdentifier: "signInViewController") as! signInViewController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewCOntroller= obj

Also, in your application(_:didFinishLaunchingWithOptions:) you have to check for your user session

此外,在您的应用程序(_:didFinishLaunchingWithOptions :)中,您必须检查您的用户会话

if API.User.CURRENT_USER != nil {
   //SET YOUR ROOT VIEW CONTROLLER HERE
}

You need set your root VC as, signInViewController or revealViewController(when the user exists)

您需要将根VC设置为signInViewController或revealViewController(当用户存在时)


推荐阅读
  • YB02 防水车载GPS追踪器
    YB02防水车载GPS追踪器由Yuebiz科技有限公司设计生产,适用于车辆防盗、车队管理和实时追踪等多种场合。 ... [详细]
  • 1Authenticator简介1.1层次结构图1.2作用职责是验证用户帐号,是ShiroAPI中身份验证核心的入口点;接口中声明的authenticate方法就是用来实现认证逻辑 ... [详细]
  • Spring Security核心概念与应用实践
    本文详细介绍了Spring Security的核心机制,包括其作为一系列过滤器的工作原理,如何实现用户认证与授权,以及常见的配置方法和高级特性如CSRF防护。 ... [详细]
  • 本文详细介绍如何在 macOS 上编译 FFmpeg 3.1.1,并将其集成到 iOS 项目中,包括必要的环境配置和代码示例。 ... [详细]
  • 作为一名在大型手机游戏公司工作的程序员,尽管主要负责游戏逻辑和内容的开发,但对iOS底层开发接触较少。现在有了iPhone和可以虚拟MAC环境的电脑,希望能找到有效的iOS开发学习路径。 ... [详细]
  • 在现代移动应用开发中,尤其是iOS应用,处理来自服务器的JSON数据是一项基本技能。无论是使用Swift还是PHP,有效地解析和利用JSON数据对于提升用户体验至关重要。本文将探讨如何在Swift中优雅地处理JSON,以及PHP中处理JSON的一些技巧。 ... [详细]
  • Django Token 认证详解与 HTTP 401、403 状态码的区别
    本文详细介绍了如何在 Django 中配置和使用 Token 认证,并解释了 HTTP 401 和 HTTP 403 状态码的区别。通过具体的代码示例,帮助开发者理解认证机制及权限控制。 ... [详细]
  • CentOS 7.6环境下Prometheus与Grafana的集成部署指南
    本文旨在提供一套详细的步骤,指导读者如何在CentOS 7.6操作系统上成功安装和配置Prometheus 2.17.1及Grafana 6.7.2-1,实现高效的数据监控与可视化。 ... [详细]
  • 本文档详细介绍了思科交换机的基本配置命令,包括进入特权模式、配置交换机名称及密码、VLAN配置、端口访问、查看配置信息、恢复出厂设置以及远程登录设置等。 ... [详细]
  • 前言Git是目前最流行的版本控制系统,在它的基础之上,GitHub和GitLab成为当前最流行的代码托管平台,它们均提供的代码评审、项目管理、持续集成等功能,越来越多的互联网企业都 ... [详细]
  • 本文详细介绍了如何在Ubuntu系统上快速安装和配置Bitnami版本的GitLab,包括下载安装文件、执行安装过程以及设置邮件服务等步骤。 ... [详细]
  • 系统:MacOS10.15.2,XCode11.3,swift5.0写作时间:2020-01-09说明Swift中的闭包(Closur ... [详细]
  • 本文详细介绍了Objective-C中的面向对象编程概念,重点探讨了类的定义、方法的实现、对象的创建与销毁等内容,旨在帮助开发者更好地理解和应用Objective-C的面向对象特性。 ... [详细]
  • iOS 小组件开发指南
    本文详细介绍了iOS小部件(Widget)的开发流程,从环境搭建、证书配置到业务逻辑实现,提供了一系列实用的技术指导与代码示例。 ... [详细]
  • 我们很高兴地宣布,GoogleDevelopers中国网站(developers.google.cn)正式发布!GoogleDevelopers中国网站 ... [详细]
author-avatar
k78283381
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有