Draw button on top of AVPlayer
You're using an AVPlayerViewController
, so there's no reason to access your application's window like in Alessandro Ornano's answer. Why reinvent the wheel? Every AVPlayerViewController
has a contentOverlayView
property which allows you to place views between the player and the controls.
First, create a new AVPlayerItem
and listen for the AVPlayerItemDidPlayToEndTimeNotification
notification on that item. Load the item into your player and begin playback.
Once the item completes, the selector your specified to listen for the AVPlayerItemDidPlayToEndTimeNotification
notification will be called. In that selector, access the contentOverlayView
directly and add your buttons:
In some view controller or other object:
let playerVC = AVPlayerViewController()
// ...
func setupPlayer {
let playerItem = AVPlayerItem(...)
playerVC.player?.replaceCurrentItemWithPlayerItem(playerItem)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VC.itemFinished), name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
self.presentViewController(playerVC, animated: true) {
self.playerVC.player?.play()
}
}
func itemFinished() {
let btn = UIButton(type: .System)
btn.addTarget(self, action: #selector(VC.buttonTapped), forControlEvents: .TouchUpInside)
self.playerVC.contentOverlayView?.addSubview(btn)
}
func buttonTapped() {
print("button was tapped")
// replay/comment logic here
}
As stated in the comments (and a rejected edit), buttons may not work in the contentOverlayView
. For an alternate solution, see Pyro's answer.
You could also subclass AVPlayerViewController
and do everything inside an instance of your subclass, but Apple warns against that:
Do not subclass
AVPlayerViewController
. Overriding this class’s methods is unsupported and results in undefined behavior.
I think the best way to make the avplayer buttons is explained here: IOS 8 Video Playback using AVPlayer and AVPlayerViewController .
So , I prefeer and agree with these instructions, but if you still want to add these buttons you can try to add them to the self.window
if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {
let myFirstButton = UIButton()
myFirstButton.setTitle("test", forState: .Normal)
window.addSubview(myFirstButton)
...
}