Balasubramanian
Balasubramanian

Reputation: 5520

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!)
}

Upvotes: 1

Views: 2161

Answers (2)

Balasubramanian
Balasubramanian

Reputation: 5520

Inside loop couldn't able to control the loop execution. So I took out the makeAnimation function from for-loop. Thanks @Rashwan L for your help.

self.callGIFAnimation(value: self.index){ (completed) in
      if(completed) {
          self.index = self.index + 1
          if self.index < gifNames.count {
                self.makeAnimation()
          }
          else {
              return
          }
      }
}

Upvotes: 0

Rashwan L
Rashwan L

Reputation: 38833

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!)
}

Upvotes: 1

Related Questions