使用 State listener Swift 5 实现 Firebase Auth 的正确方法 [英] Right way to implement Firebase Auth with State listener Swift 5

查看:58
本文介绍了使用 State listener Swift 5 实现 Firebase Auth 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 ios 开发和 Firebase 来说非常新.

very new to ios development and Firebase.

我已经实现了一个标准的普通 ui 流程,其中应用程序打开到启动画面,在那里检查用户是否已登录并根据状态将用户重定向到登录屏幕或主屏幕.我正在尝试从 auth 侦听器获取用户 ID,并且在 firebase auth 提供非 nil 用户 ID 之前,来自 userManager 的一些 getUserId 调用正在发生,并且用户总是最终进入注册屏幕.很想知道使用侦听器获取用户 ID 的最佳实践是什么.这是一些支持我正在做的事情的代码

I have implemented a standard run-of-the-mill ui flow where the app opens to a splash-screen, where it's checked whether user is signed in or not and depending on the state the user is redirected to the login screen or home screen. I'm trying to get a user id from auth listener, and some of my getUserId calls from the userManager are happening before the firebase auth gives a non-nil user id, and the user always ends up going to the registration screen. Would love to know what are the best practices for implementing fetching user id with listeners. Here's some code to support what I'm doing

class UserManager {

    static let shared = UserManager()
    private var currentUserId: String?

    private init() {
        print("init initiated")
        _ = Auth.auth().addStateDidChangeListener { (auth, user) in
            if let user = user {
            // User is signed in
                print("user id is: \(user.uid)")
                self.currentUserId = user.uid
                print("current user id loaded: \(self.currentUserId)")
            }
        }
    }

    func getCurrentUserId() -> String?{
        print("returning user id: \(currentUserId)")
        return currentUserId
    }


控制台的打印输出如下所示:(用户请求在 firebase 侦听器状态更改为非 nil 值之前启动

The print output from the console looks something like below: (The user request starts before the firebase listener state changes to non-nil value

nit initiated
returning user id: nil
nil
user id is: c0wTlE5EXaao3aO0rH9J6GKvuM43
current user id loaded: Optional("c0wTlE5EXaao3aO0rH9J6GKvuM43")

我已经尝试直接从 AppDelegate 初始化 UserManager,希望当应用程序的其余部分启动时,usermanager 的单例实例能够成功获取最新状态.但它显然不是这样工作的.

I have tried initializing the UserManager directly from AppDelegate, hoping that by the time the rest of the app starts the singleton instance of usermanager would have been successful in obtaining the latest state. But it doesn't work that way apparently.

推荐答案

为什么不尝试使用闭包完成处理程序?

Why don't you try this with a closure completion handler?

像这样:

UserManager里面声明:

var authDidChange: ((String) -> Void)?

addStateDidChangeListener内完成:

authDidChange?(user.uid)

因此,当您使用 UserManager 时,您将获得这样的身份验证更新:

So when you use your UserManager you will get the auth updates like this:

UserManager.shared.authDidChange = { userId in
    print("The obtained user id is: ", userId)
}

这篇关于使用 State listener Swift 5 实现 Firebase Auth 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆