Search code examples
iosswift4xcode10

Swift 4 & Xcode 10. Play video on app launch, when complete, reveal view controller


Firstly, I'm totally new to Xcode 10 and Swift 4, and I've searched here but haven't found code that works.

What I'm after: On launching app to play a video which is stored locally (called "launchvideo"). On completion of video to display/move to a UIviewcontroller with a storyboard ID of "menu"

So far I have my main navigation controller with it's linked view controller. I'm guessing I need a UIview to hold the video to be played in on this page?

Is there someone who can help a new guy out? Thanks


Solution

  • Firstly change your launch screen storyboard to Main storyboard from project settings in General tab.

    Create one view controller with following name and write code to implement AVPlayer to play video.

    import UIKit
    import AVFoundation
    
    class VideoLaunchVC: UIViewController {
    
        func setupAVPlayer() {
    
            let videoURL = Bundle.main.url(forResource: "Video", withExtension: "mov") // Get video url
            let avAssets = AVAsset(url: videoURL!) // Create assets to get duration of video.
            let avPlayer = AVPlayer(url: videoURL!) // Create avPlayer instance
            let avPlayerLayer = AVPlayerLayer(player: avPlayer) // Create avPlayerLayer instance
            avPlayerLayer.frame = self.view.bounds // Set bounds of avPlayerLayer
            self.view.layer.addSublayer(avPlayerLayer) // Add avPlayerLayer to view's layer.
            avPlayer.play() // Play video
    
            // Add observer for every second to check video completed or not,
            // If video play is completed then redirect to desire view controller.
            avPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1) , queue: .main) { [weak self] time in
    
                if time == avAssets.duration {
                    let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") as! ViewController
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            }
        }
    
        //------------------------------------------------------------------------------
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        //------------------------------------------------------------------------------
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            self.setupAVPlayer()  // Call method to setup AVPlayer & AVPlayerLayer to play video
        }
    }
    

    Main.Storyboard: Video Launch VC

    Project Launch Screen File: Project Launch Screen File

    See following video also:

    https://youtu.be/dvi0JKEpNTc