John | April 1, 2019
Video Background For Your ViewController
I’ve always thought video backgrounds were a cool feature on websites, ever since back in the day when tumblr had a live cam stream of outside their office in NYC as the background for their login screen. I had forgotten how cool it was, however, I was recently reminded by OnePlus.com’s cool background on their 5g Page.
…Then, I was developing and application for a storage company and was using a picture of their storage yard in grayscale as the background for the login screen and thought it would be really cool to actually have drone flyover footage of the storage yard as the background for the login screen instead. So, I began researching how I could do that…turns out it is really not hard at all thanks to a project on github called SwiftVideoBackground, it is actually incredibly easy.
First install SwiftVideoBackground using CocoaPods. If you are using Swift 4 its:
pod 'SwiftVideoBackground', '~> 3.0'
For Swift 3 its:
pod 'SwiftVideoBackground', '0.06'
Take the video you want to use as your background and copy it to the root of your project.
Then you need to make sure your video is in your bundle. To do this select your project target and then go the “Build Phases” tab and find the “Copy Bundle Resources row”. If your video is not there you will need add it by clicking the “+” button and selecting it.
Setting The Background
Open the ViewController you want to add the video background to then inside the ViewDidLoad function add this line:
try? VideoBackground.shared.play(view: view, videoName: "video", videoType: "MOV")
And replacing the “videoName” parameter with your video name and the “videoType” parameter with its extension.
Now when you run it you should have a video background for your view controller. I’ve added some buttons and a transparent gray overlay to show how this may actually be incorporated into an application.
SwiftVideoBackground has alot more functionality than listed here so head on over to the github page and checkout it out if you plan on setting up a video background for your view controller.
StackOverflow How to play a local video with Swift?