SWIFT 3
I had the same problem. Each time my app went into the background and then back into the foreground, my AVPlayer would disappear. Below is a simpler version of the code that works for me ... I needed to reset the player on UIApplicationWillEnterForeground. I can add more code if you need it, just let me know. It seems to be working for now. Cheers!
import UIKit
import AVFoundation
class ViewController: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Be sure to add your file to your app (not in the assets folder) and add it to your target
let theURL = Bundle.main.url(forResource:"yourVideoFile", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.frame = view.layer.bounds
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
// .none is for looping videos if you uncomment "p: AVPlayerItem" below.
// .pause is to pause at the end of the video and hold the last frame
avPlayer.actionAtItemEnd = .pause
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: avPlayer.currentItem)
NotificationCenter.default.addObserver(self, selector: #selector(appMovingToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
avPlayer.play()
paused = false
}
func playerItemDidReachEnd(notification: Notification) {
print("THE END")
// uncomment the following line for a looping video
// let p: AVPlayerItem = notification.object as! AVPlayerItem
// p.seek(to: kCMTimeZero)
}
func appMovingToForeground() {
print("App moved to foreground!")
avPlayerLayer = AVPlayerLayer(player: avPlayer)
view.layer.insertSublayer(avPlayerLayer, at: 0)
// If you want your video or video loop to continue playing when app moves to foreground add:
// avPlayer.play()
// paused = false
}
}