【问题标题】:SwiftUI Firebase authentication, persist user after network connectivity got lostSwiftUI Firebase 身份验证,在网络连接丢失后保留用户
【发布时间】:2023-02-22 20:50:41
【问题描述】:

目前我正在实施一个应用程序并使用 Firebase 身份验证 如果连接丢失,我想弹出一个出现在应用程序内部的弹出窗口 不幸的是,当我切断网络连接时,应用程序会注销我不想要的用户 Xcode 也无法识别 auth.setPersistence(.local) 方法

这是我的内容视图,用于检查用户是否已登录:

struct ContentView: View {
    @EnvironmentObject var viewModel: AppViewModel
    
    var body: some View {
        NavigationView{
            if viewModel.loggedIn{
                HomeView()
            } else {
            LoginView()
            }
        }
        .onAppear {
           viewModel.loggedIn = viewModel.isSignedIN
         }
    }
}

loggedIn var 以这种方式声明:

@Published var loggedIn = false

这些是用于登录、注册和注销的方法:

  /// This function connects to the Firebase Authentication database and logs the user in
    /// - Parameters:
    ///   - email: e-mail address entered by user in order to log in
    ///   - password: password entered by user in order to log in
    func logIn(email: String, password: String) async throws {
        mail = email
        let authRes = try await auth.signIn(withEmail: email, password: password)
        loggedIn = true
    }
    
    
    /// This function signs the user up
    /// - Parameters:
    ///   - email: e-mail used for signing up
    ///   - password: password used for signing up
    func signUp(email: String, password: String) async throws {
        mail = email
        let authRes = try await auth.createUser(withEmail: email, password: password)
        loggedIn = true
    }
    
    
    /// This function logs the user out
    func logOut() {
        try? auth.signOut()
        self.loggedIn = false
        self.eventlist.removeAll()
    }

我尝试将 loggedIn 变量保存在用户默认值中,但不幸的是它不起作用

有谁知道哪种方法最适合处理这个问题?

【问题讨论】:

  • 如果您查看带有文档的 fire base,最基本的说明有一个侦听器,使用该侦听器来影响 AppStorage 变量。
  • @loremipsum 谢谢你,我会调查的!:-))
  • @loremipsum 它正在工作!谢谢

标签: ios firebase swiftui


【解决方案1】:

我怀疑您将登录用户存储在某个状态对象中,无需重新加载它。

如果您在失去连接时显示弹出窗口,请确保显示此 ui 的状态不会以某种方式触发应用程序重新加载检查登录用户的代码。如果您没有连接,您将获得注销状态。

更新逻辑以确保您只在需要时检查身份验证,而不是不断刷新它。

如果没有更多信息或一些代码可供审查,很难说更多。

【讨论】:

  • 我更新了问题并添加了重要代码......也许你现在知道更好的解决方案我尝试将登录变量保存在用户默认值中但随后它不起作用
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 2018-05-10
  • 2020-03-16
  • 1970-01-01
  • 2018-06-06
  • 2019-12-26
相关资源
最近更新 更多