Features

Developers

How to add an api.video Swift player to your iOS application

December 15, 2022 - Romain Petit in swift, iOS, Player, Swift

We have now released the Swift player! The Swift player helps you to playback your videos easily in your iOS and iPadOS applications.

In this tutorial we will see how to add the Swift player to your code.

The Swift player package allows you to use UIKit and SwiftUI to handle multi-platform projects. The Swift player package is available on both Cocoapods and Swift Package Manager (SPM).

Before starting with this tutorial, make sure that you set your minimum target to iOS 13 and above.

To just give you a quick preview, we are going to create a Swift application with an api.video player that looks like this:

Upload video

Before starting to add the api.video Swift player to your application, you need to upload at least one video to your api.video account. If you haven't yet, see how to upload a video.

You'll need a video Id to use this component and play a video from api.video. To get yours, follow these steps:

  1. Copy your API key (sandbox or production if you are subscribed to one of our plans).
  2. Go to the official api.video documentation.
  3. Log into your account in the top right corner. If it's already done, make sure that it's the account you want to use.
  4. Go to API Reference -> Videos -> List all videos
  5. On the right, be sure the Authentication section contains the API key you want to use.
  6. Generate your upload token by clicking the Try It! button in the right section
  7. Copy the videoId value of one of elements of the response in the right section.

Alternatively, you can find your video Id in the video details of your dashboard.

Add the api.video Swift player

In this section, we will go through the three main steps of adding the api.video Swift player to your iOS application.

  1. Get the latest version

    You can find it in the release page

  2. Add the ApiVideoPlayer package to your app with:

    1. SPM

      Add the following to your package.swift

dependencies: [
    .package(url: "https://github.com/apivideo/api.video-swift-player.git", from: "X.X.X"),
],
  1. Cocoapods

    add the following to your Podfile

pod 'ApiVideoPlayer', 'X.X.X'

then run :

pod install

Replace X.X.X with the latest version.

  1. UIKit

    a. Import the package

import ApiVideoPlayer

b. Instantiate the player view:

let playerView = ApiVideoPlayerView(
    frame: .zero,
    videoOptions: VideoOptions(videoId: "YOUR_VIDEO_ID", videoType: .vod)
) // replace .vod to .live to play live stream

// To play private videos use the following code
let playerView = ApiVideoPlayerView(
    frame: .zero,
    videoOptions: VideoOptions(videoId: "YOUR_VIDEO_ID", videoType: .vod, token: "YOUR_PRIVATE_TOKEN")
)

(!) Replace “YOUR_VIDEO_ID” by your own videoId to display video

(!) Replace “YOUR_PRIVATE_TOKEN” by the private token of the video to display it.

c. To get all player events (optional)

extension YourViewController: ApiVideoPlayerControllerPlayerDelegate {
    public func didPrepare() {
        // Do what you want when didPrepare is called
    }

    public func didReady() {
        // Do what you want when didReady is called
    }

    public func didPause() {
        // Do what you want when didPause is called
    }

    public func didPlay() {
        // Do what you want when didPlay is called
    }

    public func didReplay() {
        // Do what you want when didReplay is called
    }

    public func didMute() {
        // Do what you want when didMute is called
    }

    public func didUnMute() {
        // Do what you want when didUnMute is called
    }

    public func didLoop() {
        // Do what you want when didLoop is called
    }

    public func didSetVolume(_: Float) {
        // Do what you want when didSetVolume is called
    }

    public func didSeek(_: CMTime, _: CMTime) {
        // Do what you want when didSeek is called
    }

    public func didEnd() {
        // Do what you want when didEnd is called
    }

    public func didError(_: Error) {
        // Do what you want when didError is called
    }

    public func didVideoSizeChanged(_: CGSize) {
        // Do what you want when didVideoSizeChanged is called
    }
}

d. Implement the player view in your view controller and add constraints.

override func viewDidLoad() {
    ...
    self.addSubview(playerView)
    self.playerView.translatesAutoresizingMaskIntoConstraints = false
    self.playerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    self.playerView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16.0).isActive = true
    self.playerView.leadingAnchor.constraint(equalTo: self.scrollView.contentLayoutGuide.leadingAnchor,constant: 16.0).isActive = true
    self.playerView.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.size.height * 0.3).isActive = true
    ...
}

e. To use fullscreen

override func viewDidAppear(_ animated: Bool) {
    ...
    playerView.viewController = self
    ...
}
  1. SwiftUI

    a. Import the ApiVideoPlayer package

import ApiVideoPlayer

b. In your view you have to instantiate the player and the player events in the init method

struct ContentView: View {
	...
	private var player: ApiVideoPlayer
	init() {
	    let events = PlayerEvents(
	        didPause: { () in
	            print("paused")
	        },
	        didPlay: { () in
	            print("play")
	        },
	        didReplay: { () in
	            print("video replayed")
	        },
	        didLoop: { () in
	            print("video replayed from loop")
	        },
	        didSeek: { from, to in
	            print("seek from : \(from), to: \(to)")
	        },
	        didError: { error in
	            print("error \(error)")
	        }
	    )
            self.player = ApiVideoPlayer(
                videoOptions: VideoOptions(videoId: "YOUR-VIDEO-ID", videoType: .vod),
                events: events
           ) // replace .vod to .live to play livestream
	}
	...
}

(!) Replace “YOUR_VIDEO_ID” by your own videoId to display video

If you want to play private videos:

self.player = ApiVideoPlayer(
        videoOptions: VideoOptions(videoId: "YOUR-VIDEO-ID", videoType: .vod, token: "YOUR_PRIVATE_TOKEN"),
        events: events
)

c. In the body you have to add the player with the specification you want

var body: some View {
	...
	player
		.frame(height: 250)
	...
}

You will be able to use all the methods available externally, by calling player.methodName, for example :

player.play()

If you're looking for an easy way to integrate video into your application, check out our docs and sign up for a free account.

Romain Petit

Mobile Developer

Create your free account

Start building with video now