Prevent memory leak, high memory usage using video(AVPlayer)?

I made an app in which there is a View Controller which which has a view and some buttons in it. On the view I show a 2sec long video, which repeats continuously.

I used instruments to check my memory usage. It showed me that my app's memory usage continuously increases at the View Controller where the video is. After 30 sec my app gets up to 1gb memory usage.

In the code I made a weak variable which breaks the retain cycle, so when I go from the View Controller which shows the video to an another View Controller, then my memory usage drops.

BUT: My purpose is to get dropped the memory usage each time the video starts repeating, or is there something else what I should consider to do?

Thank you in advance!

backView is the view I am using for showing the video.

//     Set up the video player.

var startVideo = true

private func playVideo(exercise : String, type : String) {

    guard let path = Bundle.main.path(forResource: exercise, ofType: type) else {
        debugPrint("video.mp4 not found")
        return
    }
    weak var player = AVPlayer(url: URL(fileURLWithPath: path))
    let playerController = AVPlayerViewController()
    playerController.player = player
    let playerLayerAV = AVPlayerLayer(player: player)
    //now we set the size of frame to be like the view ("backview")
    playerLayerAV.frame = backView.bounds
    // the backview is the view i'm using it to insert a video
    backView.layer.addSublayer(playerLayerAV)
    player!.play()

    if startVideo == true {
        player!.play()
    }else if startVideo == false {
        player?.pause()
    }

    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player!.currentItem, queue: .main) { _ in
        player!.seek(to: kCMTimeZero)
        player!.play()
    }

}

1 answer

  • answered 2018-10-11 20:26 Ashley Mills

    Try the following to continually loop a video

    let playerItem = AVPlayerItem(url: selectedItem)
    let player = AVQueuePlayer(playerItem: playerItem)
    let playerLooper = AVPlayerLooper(player: player, templateItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)
    
    player.play()