Swift中两个认证命令都不失败时才执行



我正在尝试在Firebase中注册一个用户,并将该用户添加到"users"具有附加字段的集合。当注册一个用户,我只希望这些命令执行,如果他们都是成功的。例如,如果无法将用户添加到用户集合中,我不想在Firebase中注册该用户。但是,如果firebase createUser函数失败,我也不希望将用户添加到用户集合中。

func register(withEmail email: String, password: String, fullname: String, username: String) {

Auth.auth().createUser(withEmail: email, password: password) { [self] result, error in
if let error = error {
print("Failed to register with error (error.localizedDescription)")
return
}

guard let user = result?.user else { return }

let data = ["email": email,
"username": username.lowercased(),
"fullname": fullname,
"uid": user.uid,
"listOfUserActions": listOfUserActions]

Firestore.firestore().collection("users")
.document(user.uid)
.setData(data) { _ in
self.didAuthenticateUser = true
}
}
}

我现在设置的方式是,如果用户被添加到FirebaseAuth但是post到"users"失败了,如果我的功能依赖于"用户",这不会破坏应用程序吗?收集?

您可以使用createUser和setData方法的组合方法,以确保在将didAuthenticateUser设置为true之前,这两个操作都成功。

修改后的代码:

func register(withEmail email: String, password: String, fullname: String, username: String) {
Auth.auth().createUser(withEmail: email, password: password) { [self] result, error in
if let error = error {
print("Failed to register with error (error.localizedDescription)")
return
}

guard let user = result?.user else { return }

let data = ["email": email,
"username": username.lowercased(),
"fullname": fullname,
"uid": user.uid,
"listOfUserActions": listOfUserActions]

Firestore.firestore().collection("users")
.document(user.uid)
.setData(data) { error in
if let error = error {
print("Failed to set data with error (error.localizedDescription)")
return
}
self.didAuthenticateUser = true
}
}
}

相关内容

最新更新