【问题标题】:Is firebase checking for user first timefirebase 是第一次检查用户吗
【发布时间】:2017-01-26 21:42:21
【问题描述】:

在初始加载时,firebase 告诉我,如果用户通过触发事件登录,如下所示:

firebase.auth().onAuthStateChanged(func...)

我想检查一下,firebase 是否仍在检查它。就像在页面加载时显示微调器一样,等待 firebase 检查用户,然后显示应用程序或登录/注册表单,考虑是否找到用户。

现在我只需要显示页面,然后初始化 firebase,然后,如果 firebase 找到用户,则重定向到应用程序。

【问题讨论】:

    标签: firebase login firebase-authentication


    【解决方案1】:

    您可以使用登录成功返回的FIRAuthDataResult对象从additionalUserInfo属性判断用户是否为新用户:

    Auth.auth().signIn(with: credential) { (authResult, error) in
      if let error = error {
         print(error.localizedDescription)
         return
      }
      // User is signed in
      // ...
    
      //Check if new user
      if let isNewUser: Bool = authResult?.additionalUserInfo?.isNewUser {
         if isNewUser {
            print("new user")
         }
      }
    }
    

    【讨论】:

      【解决方案2】:

      斯威夫特 4

      方法一

      检查用户的自动创建时间是否等于上次登录时间(如果确实是首次登录,则为首次登录时间)

       //Current user metadata reference
       let newUserRref = Auth.auth().currentUser?.metadata
      
       /*Check if the automatic creation time of the user is equal to the last 
         sign in time (Which will be the first sign in time if it is indeed 
         their first sign in)*/
      
       if newUserRref?.creationDate?.timeIntervalSince1970 == newUserRref?.lastSignInDate?.timeIntervalSince1970{
           //user is new user
           print("Hello new user")
       }
       else{
           //user is returning user
           print("Welcome back!")
       }
      

      方法二

      或者,您可以在 App Delegate 中设置全局变量。如果用户已经存在,我使用过的大多数应用程序都使用自动 Firebase 登录;这意味着它不会更新 lastSignInDate 值,因此仍将用户显示为新用户。

      因此,首先在类上方的 AppDelegate 中创建一个变量,如下所示:

      var newUser = false
      
      @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate{
      

      然后,每当您调用函数来创建新的 Firebase 用户时,请将 newUser 设置为 true:

      newUser = true
      

      最后,做一个 if 语句来过滤你的主控制器接收的用户:

      Override func viewDidLoad() {
         super.viewDidLoad()
            if newUser == true{
                print("welcome new user")
      
              showOnboarding()
            }
            else{
              print("Welcome back!")
            }
      }
      

      现在,只要现有用户登录,该变量将保持为 false

      【讨论】:

      • 对我来说 newUserRref?.creationDate?.timeIntervalSince1970 和 newUserRref?.lastSignInDate?.timeIntervalSince197 几乎相同,但在小数点后第三位不同(一个是 15536​​23223.055,另一个是 15536​​23223.057)。我添加了一种截断这些的方法,然后方法 1 起作用了。
      【解决方案3】:

      传递给onAuthStateChanged 的侦听器将使用nullUser 实例的参数调用。

      因此可以安全地假设 Firebase 正在检查您调用 initializeApp 和调用 onAuthStateChanged 的侦听器之间的身份验证状态。调用 initializeApp 时显示微调器,调用侦听器时隐藏它。

      【讨论】:

      • 谢谢!我没有注意到这个监听器也被null 调用。我的错。
      猜你喜欢
      • 2019-01-05
      • 2018-07-25
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多