[英]How to check if a user already exists in a Firestore collection after signing in with Firebase Auth in SwiftUI
@Published var isNewUser: Bool?
init() {
self.isNewUser = false
}
func checkIfTheUserExistsInDataBase(
userID: String?, completion: @escaping (_ isNewuser: Bool) -> Void
) {
let docRef = db.collection("users").whereField("user_id", isEqualTo: userID!).limit(to: 1)
docRef.getDocuments { querySnapshot, error in
if error != nil {
print(error?.localizedDescription)
} else {
if let doc = querySnapshot?.documents, doc.isEmpty {
completion(true)
} else {
completion(false)
}
}
}
}
func login(
email: String, password: String,
completion: @escaping (_ error: Error?, _ isEmailVerified: Bool) -> Void
) {
Auth.auth().signIn(withEmail: email, password: password) { authDataResult, error in
if error == nil {
if authDataResult!.user.isEmailVerified {
DispatchQueue.main.async {
self.checkIfTheUserExistsInDataBase(userID: authDataResult?.user.uid) { isNewUser in
self.isNewUser = isNewUser
}
}
UserDefaults.standard.set(authDataResult?.user.uid, forKey: CurrentUserDefaults.userID)
completion(error, true)
} else {
print("Email not verified")
completion(error, false)
}
} else {
completion(error, false)
}
}
}
I tried to use DispatchSemaphore
to let a longer running function execute first which is checkIfTheUserExistsInDataBase
, but it froze my app.我尝试使用DispatchSemaphore
让运行时间更长的 function 首先执行,即checkIfTheUserExistsInDataBase
,但它冻结了我的应用程序。 Is there a better way to do this?有一个更好的方法吗?
Firebase supports async/await (see this short , this video , and this blog post I created to explain this in detail. Firebase 支持 async/await(参见这个短片、这个视频和我创建的这篇博文来详细解释这一点。
To answer your question: you should use async/await to call signing in the user, waiting for the result, checking if the user exists in your Firestore collection, and the updating the UI.要回答您的问题:您应该使用 async/await 来调用用户登录,等待结果,检查用户是否存在于您的 Firestore 集合中,以及更新 UI。
The following code snippet (which is based on this sample app ) uses the new COUNT
feature in Firestore to count the number of documents in the users
collection to determine if there is at least one user with the ID of the user that has just signed in.以下代码片段(基于此示例应用程序)使用 Firestore 中新的COUNT
功能来计算users
集合中的文档数量,以确定是否至少有一个用户的 ID 为刚刚登录的用户.
func isNewUser(_ user: User) async -> Bool {
let userId = user.uid
let db = Firestore.firestore()
let collection = db.collection("users")
let query = collection.whereField("userId", isEqualTo: userId)
let countQuery = query.count
do {
let snapshot = try await countQuery.getAggregation(source: .server)
return snapshot.count.intValue >= 0
}
catch {
print(error)
return false
}
}
func signInWithEmailPassword() async -> Bool {
authenticationState = .authenticating
do {
let authResult = try await Auth.auth().signIn(withEmail: self.email, password: self.password)
if await isNewUser(authResult.user) {
}
return true
}
catch {
print(error)
errorMessage = error.localizedDescription
authenticationState = .unauthenticated
return false
}
}
See this video for more details about how to implement Firebase Authentication in SwiftUI apps.有关如何在 SwiftUI 应用程序中实施 Firebase 身份验证的更多详细信息,请观看此视频。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.