【发布时间】:2020-07-29 00:29:39
【问题描述】:
我遇到了 Firebase 快照的问题。我成功地将我的 Fierbase 帐户与我的 Xcode 项目联系起来。我能够更改 Firestore 云中的数据。但我无法阅读。这是我的功能:
class UserService{
static func CheckIfMoreThanOneUserIsLoggedIn() -> Bool{
var BoolenToReturn:Bool?
let AuthUser = Auth.auth().currentUser
let userId = AuthUser!.uid
let localDeviceString = Constants.UserDefaultsStorage.string(forKey: userId)
// LocalDeviceString is generated (20 random letters) when the user is logged in succesfully.
//This DeviceString would be stored on one hand in the cloud on the other hand on the device.
//When the user open the Application it checks if the localDeviceString of the cloud is the same as the String stored on the device.
//I’m able to denie the user access through multiple devices simultaneously (-> Any imporvent is desired)
let newUserReference = Firestore.firestore().collection("users").document(userId)
newUserReference.getDocument {
(querySnapshot, err) in // Code never runs the closure
guard err != nil else {
return
}
for document in querySnapshot!.data()! {
if document.key == "RandomString" {
let docValue:String = document.value as! String
if docValue == localDeviceString{
BoolenToReturn = true
}
else{
BoolenToReturn = false
}
}
}
}
return BoolenToReturn ?? false
}
}
编辑
基于@Frank van Puffelen 的链接,我能够制定自己的解决方案。但是这个程序并没有我想要的那么专业,因为现在它是在LaunchViewController 中定义的一个函数。此外,我在newUserReference.getDocument 的闭包中调用了HomeViewController 的segue。我不想实现的目标:在 UserService 类中定义的一个函数,如果允许用户使用该应用程序,它将返回一个布尔值。
【问题讨论】:
-
数据从 Firestore 异步加载。这意味着当您的
return BoolenToReturn ?? false运行时,for document in querySnapshot!.data()! ...尚未被调用。有关这方面的更多信息,请参阅 stackoverflow.com/questions/52244924/… 和其中许多 stackoverflow.com/… -
感谢您的参考。我一定会检查出来的。看来您对 Firebase 了解很多。您知道如何改进算法以拒绝用户同时通过多个设备访问吗?
-
newUserReference.getDocument { -
我猜这是个误会。我在“编辑”中更准确地描述了这种情况。谢谢提及。
标签: ios swift firebase google-cloud-firestore