热门标签 | 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(当用户存在时)


推荐阅读
  • 本文介绍了UVALive6575题目Odd and Even Zeroes的解法,使用了数位dp和找规律的方法。阶乘的定义和性质被介绍,并给出了一些例子。其中,部分阶乘的尾零个数为奇数,部分为偶数。 ... [详细]
  • 本文介绍了MVP架构模式及其在国庆技术博客中的应用。MVP架构模式是一种演变自MVC架构的新模式,其中View和Model之间的通信通过Presenter进行。相比MVC架构,MVP架构将交互逻辑放在Presenter内部,而View直接从Model中读取数据而不是通过Controller。本文还探讨了MVP架构在国庆技术博客中的具体应用。 ... [详细]
  • iOS开发Debug和Release的理解
    2019独角兽企业重金招聘Python工程师标准参考:http:blog.csdn.netmad1989articledetails406580331&# ... [详细]
  • 篇首语:本文由编程笔记#小编为大家整理,主要介绍了预加载多个本地WebView相关的知识,希望对你有一定的参考价值。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • Gitlab接入公司内部单点登录的安装和配置教程
    本文介绍了如何将公司内部的Gitlab系统接入单点登录服务,并提供了安装和配置的详细教程。通过使用oauth2协议,将原有的各子系统的独立登录统一迁移至单点登录。文章包括Gitlab的安装环境、版本号、编辑配置文件的步骤,并解决了在迁移过程中可能遇到的问题。 ... [详细]
  • Android源码中的Builder模式及其作用
    本文主要解释了什么是Builder模式以及其作用,并结合Android源码来分析Builder模式的实现。Builder模式是将产品的设计、表示和构建进行分离,通过引入建造者角色,简化了构建复杂产品的流程,并且使得产品的构建可以灵活适应变化。使用Builder模式可以解决开发者需要关注产品表示和构建步骤的问题,并且当构建流程发生变化时,无需修改代码即可适配新的构建流程。 ... [详细]
  • imnewtotheswiftandxcodeworld,soimhavingaproblemtryingtointegrateapackagetomypro ... [详细]
  • 1.webkit内核中的一些私有的meta标签,这些meta标签在开发webapp时起到非常重要的作用(1) ... [详细]
  • iOS 苹果开发证书失效的解决方案(Failed to locate or generate matching signing assets)
    从2月14日开始,上传程序的同学可能会遇到提示上传失败的提示.并且打开自己的钥匙串,发现所有的证书全部都显示此证书签发者无效.出现以下情况:Failedtolocateorgene ... [详细]
  • UMTS基础知识汇总
    协议框架23G接口UMTS实体EntityNameDescriptionAuCAuthenticationCenterCBCCellBroadcastCenterC-RNCCon ... [详细]
  • iOS Xcode汇编模式切换的方法介绍
    一、概念 1.汇编指令:模拟器上运行的是Intel指令,而真机上运行的是arm指令, 2.每条汇编指令的格式总是由: 操作码,操作 ... [详细]
  • 在应用开发中少不了界面元素的布局、适配、自适应。之前苹果已经为我们提供了 AutoLayout 和 SizeClasses,方便我们实现页面的自适应弹性布局。但对于一些复杂的交互界 ... [详细]
  • iOS推送手机消息的技术背后的奥秘揭示
    作者:allenzzhao,腾讯IEG运营开发工程师消息推送我们几乎每天都会用到,但你知道iOS中的消息推送是如何实现的吗?本文将从推送权限申请,到本地和远程消息推送, ... [详细]
  • 2015年iOS测试现状
    本文由伯乐在线-nathanw翻译,dopcn校稿。未经许可,禁止转载!英文出处:www.mokacoding.com。欢迎加入翻译小组。几周前,我决定将将我在mokacoding ... [详细]
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社区 版权所有