YouTubePlayerKit

repository·main·Indexed 21 days ago

https://github.com/sventiigi/youtubeplayerkit

A Swift package providing a native interface for playing YouTube videos in SwiftUI, UIKit, and AppKit applications across iOS, macOS, and visionOS. It acts as a wrapper around the YouTube iFrame API, offering components like YouTubePlayerView, YouTubePlayerViewController, and YouTubePlayerHostingView, along with support for playback control, event observation via Combine, and custom JavaScript execution.

Tokens
4.2K
Snippets
13
Records
18
Agent score
26%

What's inside YouTubePlayerKit

  1. Supported platforms and frameworks for YouTubePlayerKit

    main

    YouTubePlayerKit is designed for cross-platform development and supports the following environments:

    • Frameworks: SwiftUI, UIKit, and AppKit.
    • Platforms: iOS, macOS, and visionOS.

    Important Limitations:

    • Audio background playback is not supported.
    • Simultaneous playback of multiple YouTube players is not supported.
    • Controlling playback of 360° videos is not supported.
  2. Initialize and configure a YouTubePlayer

    main

    The YouTubePlayer is the central object for interacting with the YouTube iFrame API. You can initialize it with a simple URL string or with full control using Source, Parameters, and Configuration.

    • Source: Defines what to play (video, playlist, channel, etc.).
    • Parameters: Controls the behavior and style of the YouTube player (e.g., autoPlay, loopEnabled, showControls). Note: Updating parameters at runtime causes the player to reload.
    • Configuration: Linked to the underlying web view (e.g., fullscreenMode, allowsInlineMediaPlayback). Configuration cannot be modified after instantiation.
    let youTubePlayer = YouTubePlayer(
        // Possible values: .video, .videos, .playlist, .channel
        source: .video(id: "psL_5RIBqnY"),
        // The parameters of the player
        parameters: .init(
            autoPlay: true,
            loopEnabled: true,
            startTime: .init(value: 5, unit: .minutes),
            showControls: true
        ),
        // The configuration of the underlying web view
        configuration: .init(
            fullscreenMode: .system,
            allowsInlineMediaPlayback: true,
            customUserAgent: "MyCustomUserAgent"
        )
    )
  3. Quickstart: Display a YouTube video in SwiftUI

    main

    To display a YouTube video in a SwiftUI application, import YouTubePlayerKit and use the YouTubePlayerView component. You can pass a video URL string directly to the initializer to get started with a single line of code.

    import SwiftUI
    import YouTubePlayerKit
    
    struct ContentView: View {
    
        var body: some View {
            //  WWDC 2019 Keynote
            YouTubePlayerView(
                "https://youtube.com/watch?v=psL_5RIBqnY"
            )
        }
    
    }
  4. Configure macOS/Mac Catalyst network permissions

    main
    When integrating YouTubePlayerKit into a macOS or Mac Catalyst target, you must enable "Outgoing Connections (Client)" in the "Signing & Capabilities" section of your project settings to allow the player to connect to YouTube.
  5. Install YouTubePlayerKit via Swift Package Manager

    main

    To integrate YouTubePlayerKit into your project using Swift Package Manager, add it as a dependency in your Package.swift file:

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

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

  6. Customize underlying HTML with HTMLBuilder

    main

    For advanced customization of the underlying HTML, you can provide a custom YouTubePlayer.HTMLBuilder during YouTubePlayer initialization. This allows you to override the JavaScript variable name, URL schemes, and provide a custom htmlProvider closure to return a custom HTML string.

    let youTubePlayer = YouTubePlayer(
        source: .video(id: "psL_5RIBqnY"),
        configuration: .init(
            htmlBuilder: .init(
                youTubePlayerJavaScriptVariableName: "youtubePlayer",
                youTubePlayerEventCallbackURLScheme: "youtubeplayer",
                youTubePlayerEventCallbackDataParameterName: "data",
                youTubePlayerIframeAPISourceURL: .init(string: "https://www.youtube.com/iframe_api")!,
                htmlProvider: {
                    htmlBuilder, jsonEncodedYouTubePlayerOptions in
                    // TODO: Return custom HTML string
                }
            )
        )
    )
  7. Display YouTube videos in SwiftUI

    main

    In SwiftUI, use YouTubePlayerView to display a YouTubePlayer. You can provide a simple URL string or a YouTubePlayer instance. YouTubePlayerView also supports an optional overlay closure to handle different player states like .idle, .ready, or .error.

    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
                // An optional overlay view for the current state of the player
                switch state {
                case .idle:
                    ProgressView()
                case .ready:
                    EmptyView()
                case .error(let error):
                    ContentUnavailableView(
                        "Error",
                        systemImage: "exclamationmark.triangle.fill",
                        description: Text("YouTube player couldn't be loaded: \(error)")
                    )
                }
            }
            // Optionally react to specific updates such as the fullscreen state
            .onReceive(
                self.youTubePlayer.fullscreenStatePublisher
            ) { fullscreenState in
                if fullscreenState.isFullscreen {
                    // ...
                }
            }
        }
    
    }
  8. Display YouTube videos in UIKit or AppKit

    main

    For UIKit or AppKit applications, use YouTubePlayerViewController or YouTubePlayerHostingView. Both allow you to pass a YouTubePlayer instance (or a URL string) and provide access to the player via the .player property.

    import UIKit
    import YouTubePlayerKit
    
    let youTubePlayerViewController = YouTubePlayerViewController(
        player: "https://youtube.com/watch?v=psL_5RIBqnY"
    )
    
    let youTubePlayerHostingView = YouTubePlayerHostingView(
        player: "https://youtube.com/watch?v=psL_5RIBqnY"
    )
    
    // Access the player on both instances via the `.player` property
    // Example: youTubePlayerViewController.player
  9. Observe player changes with Publishers

    main

    You can react to player updates (like playback metadata changes) using Combine Publishers provided by the YouTubePlayer instance.

    // Observe playback metadata
    let cancellable = youTubePlayer
        .playbackMetadataPublisher
        .sink { playbackMetadata in
            // ...
        }
  10. Control playback and handle API errors

    main

    Most YouTubePlayer API methods are async and throwable. If a command fails, it throws a YouTubePlayer.APIError, which provides details like the reason, underlyingError, the executed javaScript, and the javaScriptResponse.

    // Pauses the currently playing video
    try await youTubePlayer.pause()
    
    // Error handling example
    do {
        try await youTubePlayer.setCaptions(fontSize: .small)
    } catch {
        print(
            "Failed to set captions font size",
            error.reason,
            error.underlyingError,
            error.javaScript,
            error.javaScriptResponse
        )
    }
  11. Initialize a YouTubePlayer

    main

    You can create a YouTubePlayer instance using several different initializers depending on your source requirements:

    • init(url:): Initialize using a URL object.
    • init(urlString:): Initialize using a video URL string.
    • init(source:parameters:configuration:isLoggingEnabled:): A comprehensive initializer for fine-grained control over the player source, iFrame parameters, configuration, and logging.
  12. Enable and manage logging

    main

    You can monitor the communication between the library and the YouTube Player iFrame JavaScript API using the unified logging system (OSLog). This is useful for debugging player options, JavaScript events, and evaluations.

    • Enable logging during initialization using the isLoggingEnabled parameter.
    • Toggle logging at runtime by updating the isLoggingEnabled property on the YouTubePlayer instance.
    • Access the underlying Logger instance via the logger() method if logging is enabled.
    // Enable or disable logging during initialization
    let youTubePlayer = YouTubePlayer(
        source: [
            "w87fOAG8fjk",
            "RXeOiIDNNek",
            "psL_5RIBqnY"
        ],
        isLoggingEnabled: true
    )
    
    // To update during runtime update the isLoggingEnabled property
    youTubePlayer.isLoggingEnabled = false
    
    // Additionally, you can retrieve an instance of the logger if logging is enabled.
    let logger: Logger? = youTubePlayer.logger()