【发布时间】:2021-01-02 17:01:56
【问题描述】:
提前致谢!我目前正在尝试学习如何使用 SwiftUI 构建移动应用程序,并希望将 Firebase 用于基于云的服务(数据库、身份验证)。我在尝试实现闭包以确保继续执行的代码仅在执行 Firebase 任务后执行时遇到了一些麻烦。我尝试在我的 findUser() 函数中编写一个闭包和 @escaping 函数,但我的常规程序仍然没有等待 findUser() 完成后再继续。
这里有什么想法吗?我在下面粘贴了我的 findUser() 函数,以及我目前如何调用它
func findUser(searchKey: String, searchValue: Any, completionHandler: @escaping (_ result: Dictionary<String, Any>?) -> Void) {
var user: Dictionary<String, Any>? = nil
let db: Firestore = getFirebaseConn()
let usersRef = db.collection(fire.userPath) // db ref
usersRef.whereField(searchKey, isEqualTo: searchValue).getDocuments() { (querySnapshot, err) in
guard let querySnapshot = querySnapshot else {
print("There was an error with retrieving the query snapshot")
completionHandler(user)
return
}
if let err = err {
print("There was an error finding the user: \(err)")
completionHandler(user)
return
}
let docsList = querySnapshot.documents
if docsList.count == 1 { // expected case we want
print("Found by \(searchKey)!") // temp
user = docsList[0].data()
} else if docsList.count == 0 {
print("Not found by \(searchKey)!") // temp
} else { // error case...
print("Ok, we should NOT be getting more than 1 result from \(searchKey), kekw!")
}
completionHandler(user)
return
}
}
我是这样称呼它的:
var userFound: Dictionary<String, Any>?
findUser(searchKey: "email", searchValue: search) { (result) in
print("Ok we got our first result")
print(result)
if result != nil {
userFound = result!
}
}
// this chunk of code is being called BEFORE the results closure
if userFound == nil {
print("Not found!")
} else {
print("Found!")
}
补充说明:
我想实现类似的目标,
- 点击搜索
- Firebase 找到用户
- 声明用户找到
- 返回用户
目前是:
- 点击搜索
- 声明未找到用户
- 不返回任何内容
- Firebase 找到用户
修改正确的解决方案!
findUser() 不需要更改,但我的代码结构需要更改。在回调部分,需要进行此更改:
var userFound: Dictionary<String, Any>?
findUser(searchKey: "email", searchValue: search) { (result) in
print("Ok we got our first result")
print(result)
if result != nil {
userFound = result!
}
// this chunk of code is being called BEFORE the results closure
if userFound == nil {
print("Not found!")
} else {
print("Found!")
}
}
// There should NOT be code after this to mimic a synchronous step of retrieving user --> loading!
【问题讨论】:
-
当您说
"my code below this function call is NOT waiting for this closure to be completed"时,我能否澄清一下,这是指在findUser回调内部(}之前)还是外部(}之后)? -
我的程序会首先声明一个用户“未找到!”然后找到一个用户并打印该用户。这有意义吗@George_E
-
编辑有帮助。这是我的答案修复的确切解决方案,希望现在一切正常!
-
这段代码
if userFound == nil真的直接跟在findUser(searchKey后面吗?如果是这样,那就是问题所在,您已经绕过异步处理数据。代码比 Internet 更快,并且 findUser 中的代码需要一些时间才能运行,例如它依赖于 Firebase 从服务器返回的结果。只需将该代码移动到findUser闭包中即可。
标签: swift firebase firebase-realtime-database