简体   繁体   English

如何在 SwiftUI 中使用 Firebase Auth 登录后检查用户是否已存在于 Firestore 集合中

[英]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.

相关问题 如何检查 Firebase/Firestore 中的其他集合中是否存在值 - How to check if value exists in other collection in Firebase/Firestore 如何检查 firebase firestore 用户数据集合为空 - how to check firebase firestore user data collection is empty 如何检查 Firebase 集合中是否已经存在特定 ID - How to check If particular Id already in Firebase collection 如何将Firebase(Cloud Firestore)中的数据库与Laravel Auth用户集成 - How to integrate database in Firebase (Cloud Firestore) with Laravel Auth user Flutter firestore - 检查文档 ID 是否已存在 - Flutter firestore - Check if document ID already exists Firebase Android - 如何以不同用户身份登录(使用 Google 登录后) - Firebase Android - how to login as different user (after signing in with Google) 当前用户 ID 在退出后保持不变 | Firebase 认证 | Flutter Web - Current user id is persistent after signing out | Firebase Auth | Flutter Web 如何检查集合中是否存在文档 (Firebase REACT)? - How do I check if a document exists within a collection (Firebase REACT)? 如何检查该字段是否存在于 firestore 中? - How to check if the field exists in firestore? 如何检查 Cloud Firestore 中任何文档的集合中是否存在值(例如名称)? - How can I check if a value e.g. name exists in a collection within any of documents in Cloud Firestore?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM