user3069232
user3069232

Reputation: 8995

Code for fading in a video using Swift

I want to fade a video that I am playing and I did something wrong, because this code below doesn't work. Would appreciate a second pair of eyes to take a look?

  let videoURL = slide2show.aURL
  playerItem = AVPlayerItem(URL: videoURL)
  player = AVPlayer(playerItem: playerItem)
  playerLayer = AVPlayerLayer(player: player)
  playerLayer.frame = CGRect(x: 128, y: 128, width: 512, height: 256)
  dispatch_async(dispatch_get_main_queue()) { [unowned self] in

     self.playerLayer.opacity = 0.0;

     self.fadeInV = CABasicAnimation(keyPath: "opacity")
     self.fadeInV.fromValue = 0.0
     self.fadeInV.toValue = 1.0
     self.fadeInV.duration = 8.0
     self.fadeInV.delegate = self
     self.fadeInV.setValue("video", forKey:"fadeInV")
     self.fadeInV.removedOnCompletion = false
     self.fadeInV.fillMode = kCAFillModeForwards
     self.playerLayer.addAnimation(self.fadeInV, forKey: "opacity")
     self.view.layer.addSublayer(self.playerLayer)

And the call to start the Video, once faded in?

override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
    print("animationDidStop")

    let nameValue3 = anim.valueForKey("fadeInV") as? String
    if let name = nameValue3 {
        if (name == "video") {
            self.player.play()
        }
    }

Upvotes: 0

Views: 853

Answers (1)

Alexander B
Alexander B

Reputation: 137

I did it like this, but I've added other view, you can try add image

let vc: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myVC")
        self.addChildViewController(vc)
        self.view!.addSubview(vc.view!)
        UIView.animateWithDuration(0.2, animations: {() -> Void in
            vc.view.alpha = 0
            vc.view.alpha = 1
            }, completion: {(finished: Bool) -> Void in
                UIView.animateWithDuration(0.2, animations: {() -> Void in
                    vc.view.alpha = 1
                    vc.view.alpha = 0
                    }, completion: {(finished: Bool) -> Void in
                        vc.view!.removeFromSuperview()
                })
        })

Upvotes: 1

Related Questions