Balasubramanian Balasubramanian -4 years ago 55
iOS Question

Swift - How to handle completion block in for-loop?

I want to display multiple animation one after another.

gifArray
has list of animation. I'm looping this array in for-loop. What happening is last animation is getting displayed and finished.

How can I continue the each loop only when current loop animation gets finished ?

for index in 0..<gifArray.count {
self.makeAnimation(value: index)
}

func makeAnimation(value: Int){
let anotherAnimationView = LOTAnimationView(name: gifNames[value])
animationView = anotherAnimationView
animationView?.play(completion: { finished in
print("completed")
})
self.view.addSubview(animationView!)
}

Answer Source

You can add a completionHandler to your function which you can call when the animation is completed:

func makeAnimation(value: Int, onCompletion: @escaping (LOTAnimationView) -> Void) {
    let anotherAnimationView = LOTAnimationView(name: gifNames[value])
    animationView = anotherAnimationView
    animationView?.play(completion: { finished in
        print("completed")
        onCompletion(animationView)
    })
}

And to use it use the following:

makeAnimation(value: 1000000) { (animationView) in
    self.view.addSubview(animationView!)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download