注销并登录成为新用户后,Swift Firebase登录用户不会更新

时间:2020-05-23 19:34:10

标签: swift firebase google-cloud-firestore firebase-authentication swiftui

编辑:我已经设法为自己提供了解决方案。

我已经宣布 func update() { … } 在UserData类的init()函数下,该函数基本上执行与init()函数相同的代码,并且当用户登录,注册或注销时我调用self.userData.update(),因此EnvironmentObject始终保持不变最新。

当我注销当前帐户并登录到新用户时,名为UserData的EnvironmentObject将从Firestore收集所有用户的数据,该对象将不会更新,并且旧用户将代替新用户显示。我不知道如何解决此问题。当我注册一个新用户时,也会发生此问题。该用户的其他我的EnvironmentObject也不会更新。

RegisterView:

 // Registrier Button
                Button(action: {
                    if(self.password == self.passwordConfirmation) {
                        Auth.auth().createUser(withEmail: self.email, password: self.password) { (authResult, error) in
                            // Prüfen, ob Nutzer erfolgreich erstellt wurde
                            guard let user = authResult?.user, error == nil else {
                                // Fehlermeldung anzeigen
                                self.errorMessage = Text(error!.localizedDescription)
                                self.showAlert = true
                                self.alertTitle = Text("Fehler")
                                return
                            }

                            // Nutzer erfolgreich registriert
                            self.errorMessage = Text("\(user.email!) erfolgreich erstellt!")
                            self.showAlert = true
                            self.alertTitle = Text("Erfolg")

                            let db = Firestore.firestore()
                            db.collection("users").document(String(user.uid)).setData([
                                "E-Mail": self.email, "Name": self.name, "account": "user","uid": user.uid,"reserviert": "none", "customerID": "NULL"])


                            // Change View
                            self.registerSuccess = true
                        }
                    }
                    else {
                        self.errorMessage = Text("Deine Passwörter stimmen nicht überein!")
                        self.showAlert.toggle()
                    }
                }) {
                    RegisterButtonContent()
                }

LogInView:

            // Login Button
        Button(
        action: {
            Auth.auth().signIn(withEmail: self.email, password: self.password) { (authResult, error) in
                guard let user = authResult?.user, error == nil else {
                    self.errorMessage = Text(error!.localizedDescription)
                    self.showAlert = true
                    return
                }

                self.isLoggedIn = true
            }
        }) {
            LoginButtonContent()
        }.padding()

UserData,不会更新:

class UserData: ObservableObject {

//静态让共享= UserData()

@Published var user = User(id: "", name: "", email: "", account: "", reserviert: "", customerID: "")    // 0: Name; 1: E-Mail; 2: User ID; 3: User(Bool))

init ()  {
    let db = Firestore.firestore()
    guard let userID = Auth.auth().currentUser?.uid else {
        print("No user")
        return
    }
    let userData = db.collection("users").document(String(userID))

    userData.addSnapshotListener(includeMetadataChanges: true) { (snap, err) in
        guard let document = snap else {
            print("Document does not exist")
            return
        }

        guard let data = document.data() else {
            print("Document was empty")
            return
        }

        self.user = User(id: data["uid"] as! String, name: data["Name"] as! String, email: data["E-Mail"] as! String, account: data["account"] as! String, reserviert: data["reserviert"] as! String, customerID: data["customerID"] as! String)
    }
}

}

SceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

var window: UIWindow?
var data = UserData()
var lounges = getLoungeData()
var viewRouter = ViewRouter()
var reservierungsInfos = getReservierungsInfos()


func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()

    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        if Auth.auth().currentUser != nil {
            window.rootViewController = UIHostingController(rootView: contentView.environmentObject(viewRouter).environmentObject(data).environmentObject(lounges).environmentObject(reservierungsInfos))
        } else {
        window.rootViewController = UIHostingController(rootView: contentView.environmentObject(viewRouter))
        }
        self.window = window
        window.makeKeyAndVisible()
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定您期望在这里发生什么,但是一次只能 登录一个用户。如果您允许新用户登录,那么旧用户将立即注销。此行为无法更改。

相关问题