【发布时间】:2021-09-06 05:30:41
【问题描述】:
我有一个@Published 文本字段的订阅者。我通过类的 init() 函数添加订阅者。
此订阅者的地图会扫描 Firebase 中的所有用户并检查“电子邮件”字段。如果用户输入的电子邮件在这些字段之一中,那么我将 valid 设置为 false(因为该电子邮件已在使用中)。
但是,当我运行此代码时,将首先执行第二个打印行,并使用默认值。然后,一段时间后,运行 print("This email is valid") 行。
我认为这与 Firebase 调用是异步任务这一事实有关。
如何解决这个问题,以便返回值返回 Firebase 调用的结果?我使用的是 Xcode 版本 12.5.1。
另外,我不确定这是否是检查电子邮件是否已被使用的最佳方法,但这是我能找到的唯一解决方案:)
代码:
func addEmailSubscriber() {
$email
.debounce(for: .seconds(1.0), scheduler: DispatchQueue.main)
.map { email -> Bool in
var valid: Bool = false
Firestore.firestore()
.collection("users")
.whereField("email", isEqualTo: email)
.getDocuments { (snapshot, err) in
guard let snapshot = snapshot else { print("Error getting snapshot"); return }
if err != nil {
print("Error occured")
return
}
if snapshot.documents.count == 0 {
print("This email is valid") // This is successfully printed after some time
valid = true
return
}
}
print(valid) // This gets printed first, with the value of "false"
return valid
}
.sink { [weak self] isValid in
self?.emailIsValid = isValid
}
.store(in: &cancellabes)
}
【问题讨论】:
标签: swift firebase google-cloud-firestore swiftui combine