[英]Swift iOS: How to force a loop with async code to run synchronously?
So I have this code below: 所以我有下面的代码:
func handleSendPost() {
let postRef = Global.FIRDB!.child("posts").childByAutoId()
for p in postComponents {
var values: [String : Any] = ["type": p.type!.rawValue, "text": p.text]
let childRef = reference.childByAutoId()
childRef.updateChildValues(values, withCompletionBlock: {
(err, ref) in
if err != nil {
print(err)
return
}
// object successfully saved
})
}
}
It's basically an iOS app for blogging. 它基本上是一个用于博客的iOS应用。 When someone creates a post, it's broken down into components that could be text or an image. 有人创建帖子时,它会分解为可能是文本或图像的组件。 After they're done editing, it will be stored on Firebase by calling the updateChildValues
async function. 完成编辑后,将通过调用updateChildValues
异步函数将其存储在Firebase上。 The problem is that I want to maintain the order of postComponents
. 问题是我想维护postComponents
的顺序。 If I ran the code above, the order could mess up because it depends on how fast the updateChildValues
runs. 如果我运行了上面的代码,该顺序可能会混乱,因为它取决于updateChildValues
运行的速度。
I've already tried using DispatchSemaphore
(iOS 10) to no avail. 我已经尝试使用DispatchSemaphore
(iOS 10)无效。
There could be other way but I guess you could forget the loop and use recursion instead. 可能还有其他方法,但是我想您可能会忘记循环而改用递归。 The flow would be like: 流程如下:
This will send all the elements in order and stop when no more elements. 这将按顺序发送所有元素,并在没有更多元素时停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.