Aryan Sharma
Aryan Sharma

Reputation: 635

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{
        playVideo(stringArray[i].lowercaseString)
    }
}

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")
        return
    }
    player = AVPlayer(URL: NSURL(fileURLWithPath: path))
    playerLayer = AVPlayerLayer(player: player)
    //        playerController.player = player
    self.playerLayer.frame = self.view.bounds
    self.view!.layer.addSublayer(self.playerLayer)
    self.player!.play()
 //   playing = true

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

func playerDidFinishPlaying(note: NSNotification) {
    print("Video Finished")
    self.playerLayer.removeFromSuperlayer()
  //  playing = false
}

Any help would be appreciated

Upvotes: 0

Views: 489

Answers (1)

Arnab
Arnab

Reputation: 4356

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) { 
    //end 
}

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

Upvotes: 0

Related Questions