Grant Espanet Grant Espanet - 5 months ago 26
iOS Question

How to play a looping video in iOS?

How do I put an video clip in my storyboard? All I see is:

enter image description here

Also, where do I put the .mp4 file?

enter image description here

And last, what would be the correct code to include for a looping video clip when View Controller starts.

//insert looping video clip here

I am familiar with Android Studio/java and can do this there no problem. However, I am very new to swift and Xcode so I am having trouble.


To make a looping Video :-

  • Add a UIView to your ViewController, set constraints accordingly.

  • Declare that UIView as @IBOutlet in your conforming class

        @IBOutlet weak var videoView : VideoPlay!
        //Where VideoPlay is a CustomClass for the Video player
  • Create a custom Class for the video player UIVew : VideoPlay

    import UIKit
    import AVFoundation
    class VideoPlay: UIView {
         private var player : AVPlayer!
          private var playerLayer : AVPlayerLayer!
        init() {
                 super.init(frame: CGRectZero)
              override init(frame: CGRect) {
                  super.init(frame: frame)
                  self.autoresizesSubviews = false
              required init?(coder aDecoder: NSCoder) {
                  super.init(coder: aDecoder)
              private func initializePlayerLayer() {
                  playerLayer = AVPlayerLayer()
                  playerLayer.backgroundColor = UIColor.whiteColor().CGColor
                  playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
                  playerLayer.frame = self.bounds
              func playVideoWithURL(url: NSURL) {
                  player = AVPlayer(URL: url)
                  player.muted = false
                  playerLayer.player = player
              func toggleMute() {
                  player.muted = !player.muted
              func isMuted() -> Bool
                            return player.muted
              func loopVideo(videoPlayer: AVPlayer) {
                  NSNotificationCenter.defaultCenter().addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: nil, queue: nil) { notification in
  • Modify your StoryBoard conforming ViewController :-

       class ViewController: UIViewController {        
           @IBOutlet weak var videoView : VideoPlay!  
           override func viewDidLoad() {
                           let bundle: NSBundle = NSBundle.mainBundle()
                           let moviePath: String = bundle.pathForResource("FirstScreen", ofType: "mp4")!
                           let movieUrl : NSURL = NSURL.fileURLWithPath(moviePath)
  • Since the videoView conforms to class VideoPlay , You can access VideoPlay's global function.

As for where to keep the video file , keep it in the main bundle i.e :- in your case Fighting Trainer Pro Folder

Such as :-