I have a background video playing when I start my app. I want the video to pause and resume where it left off if I happen to hit the home button. Here is my code:
class ViewController: UIViewController
{
let moviePlayerController = AVPlayerViewController()
var aPlayer = AVPlayer()
func playBackgroundMovie()
{
if let url = NSBundle.mainBundle().URLForResource("IMG_0489", withExtension: "m4v")
{
aPlayer = AVPlayer(URL: url)
}
moviePlayerController.player = aPlayer
moviePlayerController.view.frame = view.frame
moviePlayerController.view.sizeToFit()
moviePlayerController.videoGravity = AVLayerVideoGravityResizeAspect
moviePlayerController.showsPlaybackControls = false
aPlayer.play()
view.insertSubview(moviePlayerController.view, atIndex: 0)
}
func didPlayToEndTime()
{
aPlayer.seekToTime(CMTimeMakeWithSeconds(0, 1))
aPlayer.play()
}
override func viewDidLoad()
{
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
playBackgroundMovie()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.didPlayToEndTime), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
Do I have to perform some actions in the app delegate? I looked at previous videos, but I think some of them are using outdated versions of swift. Or are just a little too confusing for me.
You should be able to register for a backgrounding/foregrounding notification via NSNotificationCenter to play or pause your aPlayer like so:
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(pauseVideoForBackgrounding), name: UIApplicationDidEnterBackgroundNotification, object: nil)
There are several UIApplication notification names available including UIApplicationWillEnterForegroundNotification. You can leverage as many notifications as necessary to let your video player class know what's happening with the app state.
If you're supporting iOS 8 or lower, make sure to also remove your player class as an observer from any NSNotifications you've added to your view controller.