Swift 函数从异步 firebase 调用返回一个值 [英] Swift Function returning a value from asynchronous firebase call
问题描述
我正在编写一个函数,该函数采用 groupchatID(字符串)并返回该群聊的收件人列表([字符串]).然而,我正在努力解决函数的异步部分.当我运行该函数时,它会正确地将我正在寻找的用户名数组打印到控制台.虽然,当我调用该函数并尝试打印返回值时,它始终是一个空数组,因为该函数在 firebase 调用完成之前返回该数组.我正在尝试使用回调,但我不太了解它的语法.请看一下,让我知道需要更改的内容.
I am writing a function that takes a groupchatID (String) and returns a list of Recipients ([String]) for that group chat. I am struggling with the asynchronous part of the function however. When I run the function, it correctly prints to the console the array of usernames I was looking for. Although, when I call the function and try to print the returned value, it is always an empty array because the function returns the array before the firebase call has finished. I am trying to use a callback, but I do not quite understand the syntax of it all. Please take a look and let me know what needs to be changed.
功能:
func GetRecipientsFor(GroupChatID :String , completion: @escaping ([String]) -> ()) {
var returnArray: [String] = [""]
rootRef.child("chatMembers").child(GroupChatID).observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children.allObjects {
var append = child as! FIRDataSnapshot
returnArray.append((append.key as String))
print("Return Array Currently Contains: (returnArray)")
//The above printout works properly and when the for loop finishes, the array is exactly as I want it
}
completion(returnArray)
//BUT, this portion returns an empty array
})
}
我如何调用函数:
GetRecipientsFor(GroupChatID: gchatID) { (result) -> () in
print(result)
}
新函数调用
var recipients : [String] = [""]
DispatchQueue.main.async {
GetRecipientsFor(GroupChatID: gchatID) { result in
print(result) //PRINTS CORRECTLY!!!
recipients = result
}
}
print(recipients) //PRINTS A BLANK ARRAY
推荐答案
var recipients : [String] = [""]
DispatchQueue.main.async {
GetRecipientsFor(GroupChatID: gchatID) { result in
print(result)
recipients = result
}
}
print(recipients) // Completes before recipients = result
是最后一行发生在异步调用之前.
is that the last line is happening before the async call.
进一步解释print(recipients)
发生在recipients = result
之前.所有使用接收者的逻辑都需要在该完成块内发生.你需要做的就是
To explain futher print(recipients)
happens before recipients = result
. All logic using recipients needs to happen within that completion block. All you need to do is
func getRecipients(completion: @escaping ([String]) -> ()) {
var recipients : [String] = [""]
DispatchQueue.main.async {
GetRecipientsFor(GroupChatID: gchatID) { result in
print(result)
completion(result)
}
}
}
如果你想包含更多的逻辑,你可以在完成中调用一个函数,即 handleResults(result)
.我认为阅读更多关于 闭包的信息会非常有益/completion 阻塞/和异步调用.
if you want to have further logic included you can call a function within the completion i.e. handleResults(result)
. I think it would be very beneficial to read more about closures/completion blocks/and async calls.
这篇关于Swift 函数从异步 firebase 调用返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!