gpt4 book ai didi

ios - Swift 函数从异步 firebase 调用返回值

转载 作者:行者123 更新时间:2023-11-30 10:53:30 26 4
gpt4 key购买 nike

我正在编写一个函数,它接受 groupchatID(字符串)并返回该群聊的收件人列表([字符串])。然而,我正在努力解决该函数的异步部分。当我运行该函数时,它会正确地将我正在查找的用户名数组打印到控制台。虽然,当我调用该函数并尝试打印返回值时,它始终是一个空数组,因为该函数在 firebase 调用完成之前返回该数组。我正在尝试使用回调,但我不太理解它的语法。请看一下并让我知道需要更改哪些内容。

功能:

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

最后一行发生在异步调用之前。

进一步解释 print(recipients) 发生在 recipients = result 之前。所有使用接收者的逻辑都需要在该完成 block 内发生。您需要做的就是

func getRecipients(completion: @escaping ([String]) -> ()) {
var recipients : [String] = [""]
DispatchQueue.main.async {
GetRecipientsFor(GroupChatID: gchatID) { result in
print(result)
completion(result)
}
}
}

如果您想包含更多逻辑,您可以在完成中调用一个函数,即handleResults(result)。我认为阅读更多关于 closures/completion blocks/and async calls 的内容将会非常有益。 .

关于ios - Swift 函数从异步 firebase 调用返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54209271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com