Play Looping Video using Swift

Posted on Mar 1, 2021

Playing a looping video in iOS is fairly simple but there's a catch. You need to declare AVPlayerLooper global in your class.

Below is the code:

let avPlayerItem = AVPlayerItem(url: videoOutputURL!)
let avQueuePlayer = AVQueuePlayer(playerItem: avPlayerItem)
let avPlayerLayer = AVPlayerLayer(player: avQueuePlayer)
avPlayerLooper = AVPlayerLooper(player: avQueuePlayer, templateItem: avPlayerItem)
avPlayerLayer.frame = videoPlayContainerView.bounds
avPlayerLayer.videoGravity = .resizeAspectFill
avQueuePlayer.actionAtItemEnd = .none

The videoPlayContainerView is a UIView.