Welcome back to the channel guys. Let's go ahead and continue on with our YouTube app by further improving the UISlider component and showing the current play time of our video. We'll first start by adding another UILabel that displays the play progress. Next, I'll show you how to use addPeriodicTimeObserverForInterval to capture the AVPlayer component's progress.
As a bonus, I'll teach you guys how to render how a nice gradient that makes our label components a lot more visible.
Enjoy.
!codebreak
<div class='filename'>VideoPlayerView</div>
!codebreak
!syntax-highlight
class VideoPlayerView: UIView {
//...
let currentTimeLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "00:00"
label.textColor = .whiteColor()
label.font = UIFont.boldSystemFontOfSize(13)
return label
}()
//...
override init(frame: CGRect) {
//...
controlsContainerView.addSubview(currentTimeLabel)
currentTimeLabel.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: 8).active = true
currentTimeLabel.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -2).active = true
currentTimeLabel.widthAnchor.constraintEqualToConstant(50).active = true
currentTimeLabel.heightAnchor.constraintEqualToConstant(24).active = true
//...
}
//...
private func setupPlayerView() {
//...
if let url = NSURL(string: urlString) {
//...
//track player progress
let interval = CMTime(value: 1, timescale: 2)
player?.addPeriodicTimeObserverForInterval(interval, queue: dispatch_get_main_queue(), usingBlock: { (progressTime) in
let seconds = CMTimeGetSeconds(progressTime)
let secondsString = String(format: "%02d", Int(seconds % 60))
let minutesString = String(format: "%02d", Int(seconds / 60))
self.currentTimeLabel.text = "\(minutesString):\(secondsString)"
//lets move the slider thumb
if let duration = self.player?.currentItem?.duration {
let durationSeconds = CMTimeGetSeconds(duration)
self.videoSlider.value = Float(seconds / durationSeconds)
}
})
}
}
//...
private func setupGradientLayer() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
gradientLayer.locations = [0.7, 1.2]
controlsContainerView.layer.addSublayer(gradientLayer)
}
//...
}