Hello guys, lets get back to our YouTube application today by building out the feature that allows users to watch video. I'll start off by showing you guys how to animate the video player onto the screen. Next we'll look at how to include an AVPlayer into our video view to actually start playing our video clip. We'll continue with implementing the other video player controls in the next video. Have fun.
!codebreak
<div class='filename'>FeedCell.swift</div>
!codebreak
!syntax-highlight
class FeedCell: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//...
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let videoLauncher = VideoLauncher()
videoLauncher.showVideoPlayer()
}
}
!codebreak
<div class='filename'>VideoLauncher.swift</div>
!codebreak
!syntax-highlight
import UIKit
import AVFoundation
class VideoPlayerView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .blackColor()
//warning: use your own video url here, the bandwidth for google firebase storage will run out as more and more people use this file
let urlString = "https://firebasestorage.googleapis.com/v0/b/gameofchats-762ca.appspot.com/o/message_movies%2F12323439-9729-4941-BA07-2BAE970967C7.mov?alt=media&token=3e37a093-3bc8-410f-84d3-38332af9c726"
if let url = NSURL(string: urlString) {
let player = AVPlayer(URL: url)
let playerLayer = AVPlayerLayer(player: player)
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.frame
player.play()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class VideoLauncher: NSObject {
func showVideoPlayer() {
print("Showing video player animation....")
if let keyWindow = UIApplication.sharedApplication().keyWindow {
let view = UIView(frame: keyWindow.frame)
view.backgroundColor = UIColor.whiteColor()
view.frame = CGRect(x: keyWindow.frame.width - 10, y: keyWindow.frame.height - 10, width: 10, height: 10)
//16 x 9 is the aspect ratio of all HD videos
let height = keyWindow.frame.width * 9 / 16
let videoPlayerFrame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: height)
let videoPlayerView = VideoPlayerView(frame: videoPlayerFrame)
view.addSubview(videoPlayerView)
keyWindow.addSubview(view)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .CurveEaseOut, animations: {
view.frame = keyWindow.frame
}, completion: { (completedAnimation) in
//maybe we'll do something here later...
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Fade)
})
}
}
}