This is my first attempt at fixing memory leaks for the first app that I've built. When I use the Leaks instrument, I get 1 leak on my Login View Controller and from what I can understand, it has something to do with AudioToolBox (AVFoundation) which I'm using for my looping video background.
So I thought I would try to set the AVPlayer variable to weak, but that did nothing for the leak.
How can I properly fix this leak?
Here is the code as it relates to the looping background video...
weak var player : AVPlayer?
weak var playerLayer : AVPlayerLayer?
override func viewDidLoad() {
super.viewDidLoad()
playBackgroundVideo()
}
func playBackgroundVideo() {
guard let path = Bundle.main.path(forResource: "dumbbells2480", ofType: "mov") else { return }
player = AVPlayer(url: URL(fileURLWithPath: path))
player!.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none
playerLayer = AVPlayerLayer(player: player)
playerLayer!.frame = self.view.frame
playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.view.layer.insertSublayer(playerLayer!, at: 0)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
NotificationCenter.default.addObserver(self,selector: #selector(playItem),name: UIApplication.willEnterForegroundNotification, object: nil)
player!.seek(to: CMTime.zero)
player!.play()
self.player?.isMuted = true
view.bringSubviewToFront(authStackView)
}
@objc func playerItemDidReachEnd(){
player!.seek(to: CMTime.zero)
}
@objc private func playItem() {
playerItemDidReachEnd()
player?.play()
if let playerlayer = playerLayer {
view.layer.insertSublayer(playerlayer, at: 0)
}
}
