简体   繁体   English

Swift iOS:如何强制异步代码循环同步运行?

[英]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: 流程如下:

  1. Store the elements in an array. 将元素存储在数组中。
  2. Call function that sends first element if there is at least one element in the array. 如果数组中至少有一个元素,则调用函数将发送第一个元素。
  3. In the completion block, remove the first element of the array and repeat step 2. 在完成块中,删除数组的第一个元素,然后重复步骤2。

This will send all the elements in order and stop when no more elements. 这将按顺序发送所有元素,并在没有更多元素时停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM