创建等待队列以执行动画

时间:2018-11-09 13:04:52

标签: swift asynchronous dispatch-queue

我目前正在制作快速动画。该动画由另一个函数在不稳定的时间间隔(连接到服务器)中触发。动画需要2秒钟才能完成,但是有可能在完成之前触发它。 这就是为什么我要考虑创建一个等待队列来存储触发事件,直到动画完成并可以重新开始。因此,一方面,我必须锁定动画功能,直到再次准备就绪为止;另一方面,我需要同时为传入的事件提供某种存储空间。我已经在考虑调度组,但无法弄清楚如何使用它们。 对于能够解决该问题的任何投入,我将感到非常高兴。

触发功能:

private func subscribeToNewBLock() {
        DispatchQueue.global(qos:.userInteractive).async {
            watchForNewBlock() {result in
                switch result {
                case .Failure:
                    return
                case .Success(let result):
                    //Animation function
                    self.moveBlocksDown(blockNumber: result)
                    //Recursive call to keep listening for new blocks
                    self.subscribeToNewBLock()
                }
            }
       }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使动画队列如下例所示

var results = [Int]()
var isAnimating = false

private func subscribeToNewBLock() {
    DispatchQueue.global(qos:.userInteractive).async {
        watchForNewBlock() {result in
            switch result {
            case .Failure:
                return
            case .Success(let result):

                //Call your UI operations in main thread
                DispatchQueue.main.async {

                    self.results.append(result)
                    //Animation function
                    self.moveBlocksDown()

                    //Recursive call to keep listening for new blocks
                    self.subscribeToNewBLock()
                }
            }
        }
    }
}

private func moveBlocksDown() {

    guard isAnimating == false && results.count > 0 else {

        return
    }

    self.moveBlocksDown(blockNumber: results.first!)

}

private func moveBlocksDown(blockNumber:Int){

    isAnimating = true

    UIView.animate(withDuration: 2.0, animations: {

        //Animation code goes here

    }) { (completed) in

        if completed{

            //Add follwing code in place of animation completed(May be in completion handler)
            self.isAnimating = false
            self.results = self.results.filter{$0 != blockNumber} //Remove already animated blockNumber
            self.moveBlocksDown() //Call moveBlocksDown function to check if anything pending in queue
        }
    }
}