ios – The right way to Loop Video after One other Transition Video?

Spread the love

I’ve lately began touching swiftUI. For iOS16, I wish to use AVFoundation to play the video for transition as soon as after which loop the video for loop, however I do not know a great way to do it.

I would love to have the ability to select to play the transition video with or with out the loop video.

I requested ChatGPT3.0 and it returned the code under, however this didn’t work: after the video for transition and the video for loop performs as soon as every, nothing is displayed.
I feel it’s below NotificationCenter that’s not working, however I do not know how you can change it.

import UIKit
import AVFoundation

class LoopingPlayerUIView: UIView {
    personal let playerLayer = AVPlayerLayer()
    personal var playerLooper: AVPlayerLooper?

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been carried out")

    /// Relying in your video you may choose a correct `videoGravity` property to suit higher
    init(loopedVideoName: String,
         firstVideoName: String? = nil,
         participant: AVQueuePlayer,
         videoGravity: AVLayerVideoGravity = .resizeAspectFill) {

        tremendous.init(body: .zero)

        // Load the looped video
        guard let loopedFileUrl = Bundle.primary.url(forResource: loopedVideoName, withExtension: "mp4") else { return }
        let loopedAsset = AVAsset(url: loopedFileUrl)
        let loopedItem = AVPlayerItem(asset: loopedAsset)

        // Arrange the participant with the looped video
        participant.isMuted = true
        playerLayer.participant = participant
        playerLayer.videoGravity = videoGravity

        // Play the primary video as soon as if offered
        if let firstVideoName = firstVideoName {
            guard let firstFileUrl = Bundle.primary.url(forResource: firstVideoName, withExtension: "mp4") else { return }
            let firstAsset = AVAsset(url: firstFileUrl)
            let firstItem = AVPlayerItem(asset: firstAsset)

            playerLooper = AVPlayerLooper(participant: participant, templateItem: firstItem)

            // Observer for the tip of the primary video
            NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) { _ in
                // Change to looped video and allow looping
                self.participant.replaceCurrentItem(with: loopedItem)
                self.playerLooper = AVPlayerLooper(participant: self.participant, templateItem: loopedItem)
        } else {
            // If firstVideoName just isn't offered, arrange the looper for the looped video immediately
            playerLooper = AVPlayerLooper(participant: participant, templateItem: loopedItem)

    override func layoutSubviews() {
        playerLayer.body = bounds

Leave a Reply

Your email address will not be published. Required fields are marked *