Aryan Sharma Aryan Sharma - 1 year ago 109
iOS Question

Swift: play videos in turns from a for loop

I am working on an app where I need to play videos from a FOR loop i.e. play local video against the string provided in each iteration of the loop.

The problem is when I call the playVideo() func from the loop, all the videos play simultaneously. I want them to play one after the other and then dismiss the AVPlayerLayer i.e. remove from the superlayer.
When a single video is played, the playerLayer gets dismissed but in case of more than one, the playerLayer is intact.

How to make them play one after other?

I have read about using dispatch queues, but don't know much about them.

code :

func parseString(string: String){
var stringArray = string.componentsSeparatedByString(" ")
logTextView.text = ""
for i in 0..<stringArray.count{

var player: AVPlayer!
var playerLayer: AVPlayerLayer!

// video player

private func playVideo(name: String) {
guard let path = NSBundle.mainBundle().pathForResource(name, ofType:"mp4") else {
print("file not found")
player = AVPlayer(URL: NSURL(fileURLWithPath: path))
playerLayer = AVPlayerLayer(player: player)
// playerController.player = player
self.playerLayer.frame = self.view.bounds
// playing = true

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.playerDidFinishPlaying(_:)),
name: AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem)

func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
// playing = false

Any help would be appreciated

Answer Source

Don't use for loop then. Take an int i = 0, then increase (i++) until i becomes more than stringArray.count

if (i == stringArray.count) { 

call the function, where you are doing the above execution, from playerDidFinishPlaying(note: NSNotification). Hope this will help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download