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


推荐阅读
  • iOS 开发技巧:TabBarController 自定义与本地通知设置
    本文介绍了如何在 iOS 中自定义 TabBarController 的背景颜色和选中项的颜色,以及如何使用本地通知设置应用程序图标上的提醒个数。通过这些技巧,可以提升应用的用户体验。 ... [详细]
  • 本文详细介绍如何在 macOS 上编译 FFmpeg 3.1.1,并将其集成到 iOS 项目中,包括必要的环境配置和代码示例。 ... [详细]
  • iOS中UITabBar与UINavigationController的集成及样式自定义
    探讨如何在iOS开发中有效结合UITabBarController和UINavigationController,并实现自定义样式。项目源码已托管至GitHub:https://github.com/zcsoft/ZCTabNav ... [详细]
  • 本章将深入探讨移动 UI 设计的核心原则,帮助开发者构建简洁、高效且用户友好的界面。通过学习设计规则和用户体验优化技巧,您将能够创建出既美观又实用的移动应用。 ... [详细]
  • 作为一名在大型手机游戏公司工作的程序员,尽管主要负责游戏逻辑和内容的开发,但对iOS底层开发接触较少。现在有了iPhone和可以虚拟MAC环境的电脑,希望能找到有效的iOS开发学习路径。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 本文介绍如何通过Windows批处理脚本定期检查并重启Java应用程序,确保其持续稳定运行。脚本每30分钟检查一次,并在需要时重启Java程序。同时,它会将任务结果发送到Redis。 ... [详细]
  • RecyclerView初步学习(一)
    RecyclerView初步学习(一)ReCyclerView提供了一种插件式的编程模式,除了提供ViewHolder缓存模式,还可以自定义动画,分割符,布局样式,相比于传统的ListVi ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • 基因组浏览器中的Wig格式解析
    本文详细介绍了Wiggle(Wig)格式及其在基因组浏览器中的应用,涵盖variableStep和fixedStep两种主要格式的特点、适用场景及具体使用方法。同时,还提供了关于数据值和自定义参数的补充信息。 ... [详细]
  • 基于KVM的SRIOV直通配置及性能测试
    SRIOV介绍、VF直通配置,以及包转发率性能测试小慢哥的原创文章,欢迎转载目录?1.SRIOV介绍?2.环境说明?3.开启SRIOV?4.生成VF?5.VF ... [详细]
  • 本文探讨了使用React Native框架开发的应用,在通过AppCenter构建iOS版本时遇到的‘CopyPlistFile’命令失败的问题,并提供了详细的解决方案。 ... [详细]
  • 本文详细介绍了 GWT 中 PopupPanel 类的 onKeyDownPreview 方法,提供了多个代码示例及应用场景,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
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社区 版权所有