Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you loop AVPlayer in Swift 4?

Tags:

swift

I have used the following code:

NotificationCenter.default.addObserver(self,selector: #selector(ViewController.restartVideoFromBeginning),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: nil)

@objc func restartVideoFromBeginning()  {


    let seconds : Int64 = 0
    let preferredTimeScale : Int32 = 1
    let seekTime : CMTime = CMTimeMake(seconds, preferredTimeScale)

    player!.seek(to: seekTime)

    player!.play()

}

But the player inside restartVideoFromBeginning has a nil value, does anyone know why?

like image 398
123 Avatar asked Oct 13 '25 00:10

123


1 Answers

I tried this and it worked

Loop the video

NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: myPlayer.currentItem, queue: nil) { (_) in
            myPlayer.seek(to: CMTime.zero)
            myPlayer.play()
}
myPlayerView.layer.addSublayer(avLayer)
like image 101
123 Avatar answered Oct 14 '25 19:10

123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!