在kotlin中实现状态持久性

问题描述 投票:-1回答:1

我试图在我的Android应用程序中实现状态持久性,以便用户保持登录状态,但我无法理解文档,所以我跑到这里寻求帮助。

这是片段:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

我已经尝试了很多东西但是我不太明白他们实例化了firebase变量。

Docs有这条线:

这将更改当前保存的Auth会话的指定Auth实例上的持久性类型,并将此类型的持久性应用于将来的登录请求

但我仍然无法得到哪个Auth实例,我正在使用FirebaseAuth UI。

这是我的一些代码:

    private fun showSignInOptions() {
        startActivityForResult(
            AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setAvailableProviders(providers)
                .build(),
            RC_SIGN_IN
        )
    }

    // FirebaseUI Auth code.
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == RC_SIGN_IN) {
            val response = IdpResponse.fromResultIntent(data)

            if (resultCode == Activity.RESULT_OK) {
                // Successfully signed in
                val user = FirebaseAuth.getInstance().currentUser

                Log.d("AUTH", "Sign in SUCCESSFUL. $user")
                // ...
            } else {
                Log.d("AUTH", "Sign in failed.")
                // Sign in failed. If response is null the user canceled the
                // sign-in flow using the back button. Otherwise check
                // response.getError().getErrorCode() and handle the error.
                // ...
            }
        }


    }

我在showSignInOptions()打电话给onCreate()

在此先感谢您的帮助:D

android firebase kotlin firebase-authentication firebaseui
1个回答
0
投票

如果我正确理解您的问题,您希望让您的用户登录应用程序并且不要求他们登录。如果是这种情况,您需要做的就是检查是否

FirebaseAuth.getInstance().currentUser

返回null。如果它返回null,则可以初始化FirebaseAuthUI以使其登录。所以最终产品应该类似于以下代码段:

val mUser = FirebaseAuth.getInstance().currentUser
mUser?.let{
//do your stuff here
} ?: showSignInOptions()
© www.soinside.com 2019 - 2024. All rights reserved.