Here is an example of a fade out, which is called when a video I playing with AVPlayer finishes.
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.finishedPlaying(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
}
var fadeOut:CABasicAnimation!
func finishedPlaying(myNotification:NSNotification) {
self.commsRightNow = commsMode.appleTV.rawValue
fadeOut = CABasicAnimation(keyPath: "opacity")
fadeOut.fromValue = 1.0
fadeOut.toValue = 0.0
fadeOut.duration = 8.0
fadeOut.delegate = self
fadeOut.setValue("video", forKey:"fadeOut")
fadeOut.removedOnCompletion = false
fadeOut.fillMode = kCAFillModeForwards
playerLayer.addAnimation(fadeOut, forKey: nil)
}
You can also call the method below to do additional actions when your animation completes. This one removes the AVPlayer object altogether. Note the keys fadeOut and video are user defined values and included since you may have multiple animations starting (&stopping) that you need to identify.
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
let nameValue = anim.valueForKey("fadeOut") as? String
if let name = nameValue {
if (name == "video") {
playerLayer?.removeFromSuperlayer()
}
}
You can also call this to be triggered when you animation starts.
override func animationDidStart(anim: CAAnimation) {
// Blah Blah
}