logo

YouTubePlayerKit

A Swift Package to easily play YouTube videos

with extended support for SwiftUI, Combine and async/await


CI status


Documentation

Platform

Twitter

Example application

import SwiftUI
import YouTubePlayerKit

struct ContentView: View {
    
    var body: some View {
        //  WWDC 2019 Keynote
        YouTubePlayerView(
            "https://youtube.com/watch?v=psL_5RIBqnY"
        )
    }
    
}

Features

  • Play YouTube videos with just one line of code 📺
  • YouTube Terms of Service compliant implementation ✅
  • Access to all native YouTube iFrame APIs 👩‍💻👨‍💻
  • Support for SwiftUI and UIKit 🧑‍🎨
  • Runs on iOS and macOS 📱 🖥
  • async/await support ⛓

Example

Check out the example application to see YouTubePlayerKit in action. Simply open the Example/Example.xcodeproj and run the “Example” scheme.

Installation

Swift Package Manager

To integrate using Apple’s Swift Package Manager, add the following as a dependency to your Package.swift:

dependencies: [
    .package(url: "https://github.com/SvenTiigi/YouTubePlayerKit.git", from: "1.1.1")
]

Or navigate to your Xcode project then select Swift Packages, click the “+” icon and search for YouTubePlayerKit.

Usage

A YouTube player can be easily rendered when using SwiftUI by declaring a YouTubePlayerView.

import SwiftUI
import YouTubePlayerKit

struct ContentView: View {

    let youTubePlayer: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY"

    var body: some View {
        YouTubePlayerView(self.youTubePlayer) { state in
            // Overlay ViewBuilder closure to place an overlay View
            // for the current `YouTubePlayer.State`
            switch state {
            case .idle:
                ProgressView()
            case .ready:
                EmptyView()
            case .error(let error):
                Text(verbatim: "YouTube player couldn't be loaded")
            }
        }
    }

}

Check out the additional YouTubePlayerView initializer to place an overlay for a given state.

When using UIKit or AppKit you can make use of the YouTubePlayerViewController.

import UIKit
import YouTubePlayerKit

// Initialize a YouTubePlayerViewController
let youTubePlayerViewController = YouTubePlayerViewController(
    player: "https://youtube.com/watch?v=psL_5RIBqnY"
)

// Example: Access the underlying iFrame API via the `YouTubePlayer` instance
youTubePlayerViewController.player.showStatsForNerds()

// Present YouTubePlayerViewController
self.present(youTubePlayerViewController, animated: true)

If you wish to change the video at runtime simply update the source of a YouTubePlayer.

youTubePlayer.source = .video(id: "0TD96VTf0Xs")

Additionally, you can update the configuration of a YouTubePlayer to update the current configuration.

youTubePlayer.configuration = .init(
    isUserInteractionEnabled: true,
    autPlay: true
)

Note: Updating the YouTubePlayer.Configuration will result in a reload of the YouTubePlayer.

Since YouTubePlayer is conform to the ObservableObject protocol you can listen for changes whenever the source or configuration of a YouTubePlayer gets updated.

youTubePlayer
    .objectWillChange
    .sink { }

YouTubePlayer

A YouTubePlayer is the central object which needs to be passed to every YouTubePlayerView or YouTubePlayerViewController in order to play a certain YouTube video and interact with the underlying YouTube iFrame API.

Therefore, you can easily initialize a YouTubePlayer by using a string literal as seen in the previous examples.

let youTubePlayer: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY"

A YouTubePlayer generally consist of a YouTubePlayer.Source and a YouTubePlayer.Configuration.

let youTubePlayer = YouTubePlayer(
    source: .video(id: "psL_5RIBqnY"),
    configuration: .init(
        autoPlay: true
    )
)

Source

The YouTubePlayer.Source is a simple enum which allows you to specify which YouTube source should be loaded.

// YouTubePlayer Video Source
let videoSource: YouTubePlayer.Source = .video(id: "psL_5RIBqnY")

// YouTubePlayer Playlist Source
let playlistSource: YouTubePlayer.Source = .playlist(id: "PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092")

// YouTubePlayer Channel Source
let channelSource: YouTubePlayer.Source = .channel(name: "iJustine")

Additionally, you can use a URL to initialize a YouTubePlayer.Source

let urlSource: YouTubePlayer.Source? = .url("https://youtube.com/watch?v=psL_5RIBqnY")

When using a URL the YouTubePlayer.Source will be optional

Configuration

The YouTubePlayer.Configuration allows you to configure various parameters of the underlying YouTube iFrame player.

let configuration = YouTubePlayer.Configuration(
    // Disable user interaction
    isUserInteractionEnabled: false,
    // Enable auto play
    autoPlay: true,
    // Hide controls
    showControls: false,
    // Enable loop
    loopEnabled: true
)

let youTubePlayer = YouTubePlayer(
    source: "https://youtube.com/watch?v=psL_5RIBqnY",
    configuration: configuration
)

Check out the YouTubePlayer.Configuration to get a list of all available parameters.

API

Additionally, a YouTubePlayer allows you to access the underlying YouTube player iFrame API in order to play, pause, seek or retrieve information like the current playback quality or title of the video that is currently playing.

Check out the YouTubePlayerAPI protocol to get a list of all available functions and properties.

Async/Await

Asynchronous functions on a YouTubePlayer are generally constructed with a completion closure parameter to retrieve the result of the asynchronous operation.

// Retrieve the current PlaybackMetadata via a completion closure
youTubePlayer.getPlaybackMetadata { result in
    switch result {
    case .success(let playbackMetadata):
        print(
            "Title", playbackMetadata.title,
            "Author", playbackMetadata.author
        )
    case .failure(let youTubePlayerAPIError):
        print("Error", youTubePlayerAPIError)
    }
}

On iOS >= 15.0 and macOS >= 12.0 you can use async/await to execute the asynchronous function.

// Retrieve the current PlaybackMetadata
let playbackMetadata = try await youTubePlayer.getPlaybackMetadata()

Playback controls and player settings

// Play video
youTubePlayer.play()

// Pause video
youTubePlayer.pause()

// Stop video
youTubePlayer.stop()

// Seek to 60 seconds
youTubePlayer.seek(to: 60, allowSeekAhead: false)

Events

// A Publisher that emits the current YouTubePlayer State
youTubePlayer.statePublisher

// A Publisher that emits the current YouTubePlayer PlaybackState
youTubePlayer.playbackStatePublisher

// A Publisher that emits the current YouTubePlayer PlaybackQuality
youTubePlayer.playbackQualityPublisher

// A Publisher that emits the current YouTubePlayer PlaybackRate
youTubePlayer.playbackRatePublisher

Playback status

// Retrieve a number between 0 and 1 that specifies the percentage of the video that the player shows as buffered
youTubePlayer.getVideoLoadedFraction { _ in }

// A Publisher that emits a number between 0 and 1 that specifies the percentage of the video that the player shows as buffered
youTubePlayer.videoLoadedFractionPublisher()

// Retrieve the PlaybackState of the player video
youTubePlayer.getPlaybackState { _ in }

// Retrieve the elapsed time in seconds since the video started playing
youTubePlayer.getCurrentTime { _ in }

/// A Publisher that emits the current elapsed time in seconds since the video started playing
youTubePlayer.currentTimePublisher()

// Retrieve the current PlaybackMetadata
youTubePlayer.getPlaybackMetadata { _ in }

// A Publisher that emits the current PlaybackMetadata
youTubePlayer.playbackMetadataPublisher

Load/Cue video

// Load a new video from source
youTubePlayer.load(source: .url("https://youtube.com/watch?v=psL_5RIBqnY"))

// Cue a video from source
youTubePlayer.cue(source: .url("https://youtube.com/watch?v=psL_5RIBqnY"))

Update Configuration

// Update the YouTubePlayer Configuration
youTubePlayer.update(
    configuration: .init(
        showControls: false
    )
)

Note: updating the YouTubePlayer.Configuration will result in a reload of the entire YouTubePlayer

Changing the player volume

// Mutes the player
youTubePlayer.mute()

// Unmutes the player
youTubePlayer.unmute()

// Retrieve Bool value if the player is muted
youTubePlayer.isMuted { _ in }

// Retrieve the player's current volume, an integer between 0 and 100
youTubePlayer.getVolume { _ in }

// Sets the volume
youTubePlayer.set(volume: 50)

Retrieving video information

// Show Stats for Nerds which displays additional video information
youTubePlayer.showStatsForNerds()

// Hide Stats for Nerds
youTubePlayer.hideStatsForNerds()

// Retrieve the YouTubePlayer Information
youTubePlayer.getInformation { _ in }

// Retrieve the duration in seconds of the currently playing video
youTubePlayer.getDuration { _ in }

// A Publisher that emits the duration in seconds of the currently playing video
youTubePlayer.durationPublisher

// Retrieve the YouTube.com URL for the currently loaded/playing video
youTubePlayer.getVideoURL { _ in }

// Retrieve the embed code for the currently loaded/playing video
youTubePlayer.getVideoEmbedCode { _ in }

Playing a video in a playlist

// This function loads and plays the next video in the playlist
youTubePlayer.nextVideo()

// This function loads and plays the previous video in the playlist
youTubePlayer.previousVideo()

// This function loads and plays the specified video in the playlist
youTubePlayer.playVideo(at: 3)

// This function indicates whether the video player should continuously play a playlist
youTubePlayer.setLoop(enabled: true)

// This function indicates whether a playlist's videos should be shuffled
youTubePlayer.setShuffle(enabled: true)

// This function returns an array of the video IDs in the playlist as they are currently ordered
youTubePlayer.getPlaylist { _ in }

// This function returns the index of the playlist video that is currently playing
youTubePlayer.getPlaylistIndex { _ in }

Controlling playback of 360° videos

// Retrieves properties that describe the viewer's current perspective
youTubePlayer.get360DegreePerspective { _ in }

// Sets the video orientation for playback of a 360° video
youTubePlayer.set(
    perspective360Degree: .init(
        yaw: 50,
        pitch: 20,
        roll: 60,
        fov: 10
    )
)

Setting the playback rate

// This function retrieves the playback rate of the currently playing video
youTubePlayer.getPlaybackRate { _ in }

// This function sets the suggested playback rate for the current video
youTubePlayer.set(playbackRate: 1.5)

// This function returns the set of playback rates in which the current video is available
youTubePlayer.getAvailablePlaybackRates { _ in }

Credits

License

YouTubePlayerKit
Copyright (c) 2021 Sven Tiigi [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

GitHub

https://github.com/SvenTiigi/YouTubePlayerKit