### Basic YouTube Player Setup in SwiftUI Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Demonstrates the basic setup of a YouTubePlayerView in a SwiftUI view. It displays a loading indicator while the player is idle and shows content when ready. ```swift import SwiftUI import YouTubePlayerKit struct ContentView: View { let youTubePlayer: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" var body: some View { YouTubePlayerView(youTubePlayer) { state in switch state { case .idle: ProgressView() case .ready: EmptyView() case .error(let error): Text("Error: \(error)") } } } } ``` -------------------------------- ### Full Example: ThumbnailApp Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md A complete SwiftUI application example demonstrating how to load and display a YouTube video thumbnail from a player. ```swift @main struct ThumbnailApp: App { let player: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" var body: some Scene { WindowGroup { ContentView(player: player) } } } struct ContentView: View { let player: YouTubePlayer @State private var thumbnail: UIImage? @State private var isLoading = true var body: some View { VStack { if let thumbnail = thumbnail { Image(uiImage: thumbnail) .resizable() .scaledToFit() } else if isLoading { ProgressView() } else { Text("Failed to load thumbnail") } } .task { do { thumbnail = try await player.getVideoThumbnailImage( resolution: .maximum ) isLoading = false } catch { print("Error loading thumbnail: \(error)") isLoading = false } } } } ``` -------------------------------- ### Cue Playlist with Options Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Prepares a playlist for playback without starting it immediately. You can specify the starting video index and the time in seconds to start at within the first video. Throws an error if the playlist ID is invalid. ```swift try await youTubePlayer.cuePlaylist("PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092", index: 2, startSeconds: 30) ``` -------------------------------- ### Basic UIKit Setup Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/00-Index.md Initialize a YouTubePlayer and present it using a YouTubePlayerViewController in UIKit. ```swift import UIKit import YouTubePlayerKit let player = YouTubePlayer( source: .video(id: "psL_5RIBqnY") ) let playerViewController = YouTubePlayerViewController(player: player) addChild(playerViewController) view.addSubview(playerViewController.view) ``` -------------------------------- ### cuePlaylist Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Prepares a playlist for playback by its ID, without starting playback immediately. You can specify a starting video index and a start time in seconds for the first video. Fails if the playlist ID is invalid. ```APIDOC ## cuePlaylist ### Description Prepares a playlist to be played. ### Method `async throws` ### Parameters #### Path Parameters - **playlistId** (String) - Required - ID of the playlist to cue - **index** (Int?) - Optional - Starting video index (0-based) - **startSeconds** (Double?) - Optional - Time to start at in first video ### Throws `YouTubePlayer.APIError` — If playlist ID is invalid ### Example ```swift try await youTubePlayer.cuePlaylist("PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092", index: 2, startSeconds: 30) ``` ``` -------------------------------- ### Complete YouTube Player Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md A comprehensive example demonstrating various playback controls within a Swift class, including seeking, playing, printing playback information, and setting playback rate. ```swift import YouTubePlayerKit class PlayerController { let player: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" func playFromStart() async throws { try await player.seekTo(seconds: 0) try await player.play() } func jumpForward(_ seconds: Double) async throws { let currentTime = try await player.getCurrentTime() try await player.seekTo(seconds: currentTime + seconds) } func printPlaybackInfo() async throws { let state = try await player.getPlaybackState() let currentTime = try await player.getCurrentTime() let duration = try await player.getDuration() let quality = try await player.getPlaybackQuality() let rate = try await player.getPlaybackRate() print(""" State: \(state) Time: \(currentTime) / \(duration) seconds Quality: \(quality) Rate: \(rate) """) } func setFastPlayback() async throws { try await player.setPlaybackRate(.double) // 2x speed } } ``` -------------------------------- ### Autoplay with Start Time Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Configure the player to automatically start playing a video at a specified time. ```swift let parameters = YouTubePlayer.Parameters( autoPlay: true, startTime: .init(value: 5, unit: .minutes) ) ``` -------------------------------- ### Basic SwiftUI Setup Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/00-Index.md Initialize a YouTubePlayerView in SwiftUI with a video source and a state handler for UI updates. ```swift import SwiftUI import YouTubePlayerKit struct ContentView: View { var body: some View { YouTubePlayerView("https://youtube.com/watch?v=psL_5RIBqnY") { state in switch state { case .idle: ProgressView() case .ready: EmptyView() case .error(let error): Text("Error: \(error)") } } } } ``` -------------------------------- ### YouTubePlayer.Source Example Usage Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/08-Types-Reference.md Demonstrates creating different types of YouTubePlayer.Source and parsing from a URL. ```swift let source1 = YouTubePlayer.Source.video(id: "psL_5RIBqnY") let source2 = YouTubePlayer.Source.videos(ids: ["video1", "video2"]) let source3 = YouTubePlayer.Source.playlist(id: "PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092") let source4 = YouTubePlayer.Source.channel(name: "GoogleDevelopers") // From URL if let source = YouTubePlayer.Source(url: url) { // Use source } ``` -------------------------------- ### Autoplay with Start Time Configuration Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/README.md Configures the YouTube player to autoplay a video and start playback from a specified time. ```swift YouTubePlayer( parameters: .init( autoPlay: true, startTime: .init(value: 30, unit: .seconds) ) ) ``` -------------------------------- ### Load and Play Playlist Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Immediately loads and starts playing a specified playlist. You can optionally set the starting video index and the time in seconds to start at within the first video. Throws an error if the playlist ID is invalid. ```swift try await youTubePlayer.loadPlaylist("PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092") ``` -------------------------------- ### Example: Get Available Caption Tracks Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Retrieves a list of all available caption tracks for the player. The result is cast to an array of YouTubePlayer.CaptionsTrack. ```swift let tracks = try await youTubePlayer.getModuleOption( module: .captions, option: .tracklist, converter: .typeCast(to: [[String: Any]].self) .decode() ) as? [YouTubePlayer.CaptionsTrack] ``` -------------------------------- ### Full Player Initialization with Parameters and Configuration Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Initialize a YouTubePlayer instance with source, playback parameters, and detailed configuration options. This example combines multiple settings for comprehensive control. ```swift let player = YouTubePlayer( source: .video(id: "psL_5RIBqnY"), parameters: .init( autoPlay: true, loopEnabled: false, startTime: .init(value: 10, unit: .seconds), showControls: true, language: "en", showCaptions: true ), configuration: .init( fullscreenMode: .system, allowsInlineMediaPlayback: true, allowsPictureInPictureMediaPlayback: true, automaticallyAdjustsContentInsets: true ), isLoggingEnabled: true ) ``` -------------------------------- ### SwiftUI Basic Player Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/07-UI-Components.md Demonstrates a basic YouTubePlayerView in SwiftUI, showing a progress view while loading and an error message if playback fails. ```swift import SwiftUI import YouTubePlayerKit struct ContentView: View { var body: some View { YouTubePlayerView( "https://youtube.com/watch?v=psL_5RIBqnY" ) { state in switch state { case .idle: ProgressView() case .ready: EmptyView() case .error(let error): VStack { Image(systemName: "exclamationmark.triangle.fill") Text("Error: \(error)") } } } } } ``` -------------------------------- ### Cue Video by ID Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Prepares a specific video to be played without starting playback immediately. You can optionally specify a start time in seconds. Throws an error if the video ID is invalid. ```swift try await youTubePlayer.cueVideoById("dQw4w9WgXcQ", startSeconds: 10) ``` -------------------------------- ### Load and Play Video by ID Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Immediately loads and starts playing a specific video. You can optionally specify a start time in seconds. Throws an error if the video ID is invalid. ```swift try await youTubePlayer.loadVideoById("psL_5RIBqnY", startSeconds: 5) ``` -------------------------------- ### cueVideoById Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Prepares a specific video to be played by its ID, without starting playback immediately. Optionally, playback can be set to start at a specific time in seconds. Fails if the video ID is invalid. ```APIDOC ## cueVideoById ### Description Prepares a video to be played without immediately playing it. ### Method `async throws` ### Parameters #### Path Parameters - **videoId** (String) - Required - ID of the video to cue - **startSeconds** (Double?) - Optional - Time in seconds to start at ### Throws `YouTubePlayer.APIError` — If video ID is invalid ### Example ```swift try await youTubePlayer.cueVideoById("dQw4w9WgXcQ", startSeconds: 10) ``` ``` -------------------------------- ### YouTubePlayerViewController Basic Setup Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/07-UI-Components.md Demonstrates how to set up and embed a YouTubePlayerViewController in a UIKit view controller. Ensure you import UIKit and YouTubePlayerKit. Constraints are applied to define the player's size and position. ```swift import UIKit import YouTubePlayerKit class PlayerViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let player: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" let playerViewController = YouTubePlayerViewController(player: player) addChild(playerViewController) view.addSubview(playerViewController.view) playerViewController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ playerViewController.view.topAnchor.constraint(equalTo: view.topAnchor), playerViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), playerViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), playerViewController.view.heightAnchor.constraint( equalTo: view.widthAnchor, multiplier: 9/16 ) ]) playerViewController.didMove(toParent: self) } } ``` -------------------------------- ### Play Video Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Starts or resumes playback of the currently loaded or cued video. ```swift func play() async throws(APIError) ``` ```swift try await youTubePlayer.play() ``` -------------------------------- ### Volume Control UI Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/04-Volume-And-Mute-API.md A SwiftUI view demonstrating how to implement a user interface for controlling the YouTube player's volume and mute state. It uses a Slider for volume and buttons for mute/unmute. ```swift import SwiftUI import YouTubePlayerKit struct VolumeControlView: View { let player: YouTubePlayer @State private var volume: Int = 50 @State private var isMuted: Bool = false var body: some View { VStack(spacing: 16) { HStack { Image(systemName: isMuted ? "speaker.slash" : "speaker.wave.2") Slider(value: Binding( get: { Double(volume) }, set: { volume = Int($0) } ), in: 0...100) .onChange(of: volume) { newValue in Task { try await player.setVolume(newValue) } } Text("\(volume)%") .frame(width: 40) } HStack(spacing: 12) { Button(action: { Task { try await player.mute() isMuted = true } }) { Label("Mute", systemImage: "speaker.slash") } Button(action: { Task { try await player.unMute() isMuted = false } }) { Label("Unmute", systemImage: "speaker.wave.2") } } } .padding() .task { do { let state = try await player.getVolumeState() volume = state.volume isMuted = state.isMuted } catch { print("Failed to get volume state: \(error)") } } } } ``` -------------------------------- ### Get Video Data Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves comprehensive metadata for the current video. Use this to get details like the video title. ```swift let videoData = try await youTubePlayer.getVideoData() if let title = videoData["title"] as? String { print("Video: \(title)") } ``` -------------------------------- ### SwiftUI Custom Overlay Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/07-UI-Components.md Shows how to implement a custom overlay for YouTubePlayerView, displaying different UI elements based on the player's state (idle, ready, error). ```swift struct PlayerView: View { let player: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" var body: some View { YouTubePlayerView(player) { state in ZStack { switch state { case .idle: VStack { ProgressView() Text("Loading video...") } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.black.opacity(0.5)) case .ready: EmptyView() case .error(let error): VStack(spacing: 16) { Image(systemName: "exclamationmark.triangle") .font(.system(size: 32)) Text("Playback Error") .font(.headline) Text(String(describing: error)) .font(.caption) .foregroundColor(.gray) } .padding() .background(Color.black.opacity(0.7)) .cornerRadius(8) .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) } } } } } ``` -------------------------------- ### Playlist Navigator Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md A SwiftUI view model and view for navigating through a YouTube playlist, displaying current video information and providing controls for next/previous video. ```swift import SwiftUI import YouTubePlayerKit class PlaylistNavigator: ObservableObject { @Published var currentIndex: Int = 0 @Published var playlistSize: Int = 0 @Published var isLoading: Bool = false let player: YouTubePlayer init(player: YouTubePlayer) { self.player = player } func loadPlaylist(_ playlistId: String) async { isLoading = true do { try await player.loadPlaylist(playlistId, index: 0) await updateInfo() } catch { print("Failed to load playlist: \(error)") } isLoading = false } func nextVideo() async { do { try await player.nextVideo() await updateInfo() } catch { print("Failed to play next video: \(error)") } } func previousVideo() async { do { try await player.previousVideo() await updateInfo() } catch { print("Failed to play previous video: \(error)") } } func playVideoAt(_ index: Int) async { do { let videoIds = try await player.getPlaylist() if index >= 0, index < videoIds.count { try await player.loadVideoById(videoIds[index]) await updateInfo() } } catch { print("Failed to play video: \(error)") } } private func updateInfo() async { do { let index = try await player.getPlaylistIndex() let size = try await player.getPlaylistSize() DispatchQueue.main.async { self.currentIndex = index self.playlistSize = size } } catch { print("Failed to update playlist info: \(error)") } } } struct PlaylistNavigatorView: View { @StateObject var navigator: PlaylistNavigator var body: some View { VStack(spacing: 12) { Text("Video \(navigator.currentIndex + 1) of \(navigator.playlistSize)") .font(.headline) HStack(spacing: 16) { Button(action: { Task { await navigator.previousVideo() } }) { Label("Previous", systemImage: "backward.fill") } .disabled(navigator.currentIndex == 0 || navigator.isLoading) Button(action: { Task { await navigator.nextVideo() } }) { Label("Next", systemImage: "forward.fill") } .disabled( navigator.currentIndex >= navigator.playlistSize - 1 || navigator.isLoading ) } } .padding() } } ``` -------------------------------- ### YouTubePlayer statePublisher Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Subscribes to player state changes using Combine. This publisher emits the player's current state, allowing you to react to transitions like loading, readiness, or errors. ```swift youTubePlayer .statePublisher .sink { switch state { case .idle: print("Loading...") case .ready: print("Player ready") case .error(let error): print("Error: \(error)") } } ``` -------------------------------- ### Complete Example: Advanced Monitoring Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/11-Events-And-Observing.md This Swift code demonstrates how to create a `PlayerMonitor` class that observes multiple publishers from a `YouTubePlayer` instance. It logs events and errors, and displays the player's state, playback status, and quality in a SwiftUI `MonitorView`. This is useful for building complex UIs that require real-time feedback on the player's behavior. ```swift class PlayerMonitor: ObservableObject { @Published var playerState: YouTubePlayer.State = .idle @Published var playbackState: YouTubePlayer.PlaybackState? @Published var quality: YouTubePlayer.PlaybackQuality? @Published var eventLog: [String] = [] @Published var errorLog: [String] = [] let player: YouTubePlayer private var cancellables = Set() init(player: YouTubePlayer) { self.player = player setupObservers() } private func setupObservers() { // State changes player.statePublisher .receive(on: DispatchQueue.main) .assign(to: &$playerState) // Playback state player.playbackStatePublisher .receive(on: DispatchQueue.main) .assign(to: &$playbackState) // Quality changes player.playbackQualityPublisher .receive(on: DispatchQueue.main) .assign(to: &$quality) // Event logging player.eventPublisher .receive(on: DispatchQueue.main) .sink { [weak self] event in let logEntry = "\(Date().formatted()): \(event.name)" self?.eventLog.append(logEntry) if self?.eventLog.count ?? 0 > 100 { self?.eventLog.removeFirst() } } .store(in: &cancellables) // Error logging player.statePublisher .compactMap { state -> YouTubePlayer.Error? in if case .error(let error) = state { return error } return nil } .receive(on: DispatchQueue.main) .sink { [weak self] error in let logEntry = "\(Date().formatted()): \(error)" self?.errorLog.append(logEntry) } .store(in: &cancellables) } } struct MonitorView: View { @StateObject var monitor: PlayerMonitor var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { Section("Player State") { Text("State: \(String(describing: monitor.playerState))") if let state = monitor.playbackState { Text("Playback: \(state)") } if let quality = monitor.quality { Text("Quality: \(quality.name)") } } Section("Event Log") { ForEach(monitor.eventLog.suffix(10), id: \.self) { log in Text(log) .font(.caption) } } if !monitor.errorLog.isEmpty { Section("Error Log") { ForEach(monitor.errorLog.suffix(5), id: \.self) { log in Text(log) .font(.caption) .foregroundColor(.red) } } } } .padding() } } } ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/README.md Add YouTubePlayerKit as a dependency to your project using Swift Package Manager. Ensure you are using a compatible version. ```swift dependencies: [ .package(url: "https://github.com/SvenTiigi/YouTubePlayerKit.git", from: "2.0.0") ] ``` -------------------------------- ### SwiftUI Player with Controls Example Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/07-UI-Components.md Integrates YouTubePlayerView with custom playback controls (Play, Pause, Mute) using SwiftUI buttons and player actions. ```swift struct ControlledPlayerView: View { let player: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" var body: some View { VStack { YouTubePlayerView(player) { state in switch state { case .idle: ProgressView() case .ready: EmptyView() case .error: Text("Error loading video") } } .aspectRatio(16/9, contentMode: .fit) HStack(spacing: 16) { Button(action: { Task { try await player.play() } }) { Label("Play", systemImage: "play.fill") } Button(action: { Task { try await player.pause() } }) { Label("Pause", systemImage: "pause.fill") } Spacer() Button(action: { Task { try await player.mute() } }) { Label("Mute", systemImage: "speaker.slash") } } .padding() } } } ``` -------------------------------- ### Get Video Loaded Fraction Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Retrieves the fraction of the video that has been downloaded. Use this to check buffering progress. ```swift func getVideoLoadedFraction() async throws(APIError) -> Double ``` ```swift do { let loadedFraction = try await youTubePlayer.getVideoLoadedFraction() print("Buffered: \(Int(loadedFraction * 100))%") } catch { print("Error: \(error)") } ``` -------------------------------- ### loadPlaylist Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Loads and immediately begins playing a playlist specified by its ID. You can optionally set the starting video index and the time in seconds to begin playback in the first video. This operation will fail if the playlist ID is invalid. ```APIDOC ## loadPlaylist ### Description Immediately loads and plays a playlist. ### Method `async throws` ### Parameters #### Path Parameters - **playlistId** (String) - Required - ID of the playlist to load - **index** (Int?) - Optional - Starting video index (0-based) - **startSeconds** (Double?) - Optional - Time to start at in first video ### Throws `YouTubePlayer.APIError` — If playlist ID is invalid ### Example ```swift try await youTubePlayer.loadPlaylist("PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092") ``` ``` -------------------------------- ### Custom URL Handling Action Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Define a custom action for handling URLs tapped within the player. This example logs the URL and then opens it using the default application. ```swift let configuration = YouTubePlayer.Configuration( openURLAction: .custom { url in print("URL tapped: \(url)") DispatchQueue.main.async { UIApplication.shared.open(url) } } ) ``` -------------------------------- ### Example: Set Caption Track Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Sets the current caption track by specifying the language code. This is useful for changing the displayed subtitles. ```swift // Set caption language let languageCodeParameter: [String: String] = [ "languageCode": "en" ] try await youTubePlayer.setModuleOption( module: .captions, option: .track, value: languageCodeParameter ) ``` -------------------------------- ### Example: Get Current Caption Track Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Retrieves the information about the currently active caption track. The result is cast to YouTubePlayer.CaptionsTrack. ```swift let track = try await youTubePlayer.getModuleOption( module: .captions, option: .track, converter: .typeCast(to: [String: Any].self) .decode() ) as? YouTubePlayer.CaptionsTrack ``` -------------------------------- ### YouTubePlayer Initializer from String Literal Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Allows direct assignment of a YouTube URL string to a YouTubePlayer instance, leveraging the `ExpressibleByStringLiteral` protocol. Example: `let player: YouTubePlayer = "https://youtube.com/watch?v=..."`. ```swift nonisolated convenience init(stringLiteral urlString: String) ``` -------------------------------- ### Get Available Playback Qualities Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Retrieves an array of all available playback quality levels for the current video. This is useful for presenting quality options to the user. ```swift func getAvailablePlaybackQualities() async throws(APIError) -> [PlaybackQuality] ``` ```swift let qualities = try await youTubePlayer.getAvailablePlaybackQualities() print("Available qualities: \(qualities)") ``` -------------------------------- ### Initialize YouTubePlayer Configuration Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Set up the underlying WebKit configuration for the YouTube player, controlling aspects like fullscreen mode and media playback allowances. Configuration is immutable after player creation. ```swift let configuration = YouTubePlayer.Configuration( fullscreenMode: .preferred, allowsInlineMediaPlayback: true, allowsAirPlayForMediaPlayback: true, allowsPictureInPictureMediaPlayback: false, useNonPersistentWebsiteDataStore: false, automaticallyAdjustsContentInsets: true, customUserAgent: nil ) ``` -------------------------------- ### Get All Available Caption Tracks Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/05-Captions-API.md Fetches an array of all available caption tracks for the current video. This is useful for presenting a list of selectable caption languages to the user. ```swift let tracks = try await youTubePlayer.getCaptionsTracks() for track in tracks { print("Language: \(track.lang ?? \"Unknown\")") } ``` -------------------------------- ### Get Video URL Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves the full URL of the currently loaded video. Use this to get the direct link to the video. ```swift let url = try await youTubePlayer.getVideoUrl() print("URL: \(url)") ``` -------------------------------- ### Example: Set Captions Font Size Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Sets the font size for the captions module. The value corresponds to predefined sizes (0: small, 1: normal, 2: large, 3: extra large). ```swift // Font size values let values = [ 0: "small", 1: "normal", 2: "large", 3: "extra large" ] try await youTubePlayer.setModuleOption( module: .captions, option: .fontSize, value: 2 // Large ) ``` -------------------------------- ### Playlist Initialization and Navigation Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/00-Index.md Create a player instance with a playlist source and navigate through videos using next and previous commands. Retrieve the current playlist index. ```swift // Create playlist let source = YouTubePlayer.Source.playlist(id: "PLxx") let player = YouTubePlayer(source: source) // Navigate try await player.nextVideo() try await player.previousVideo() let index = try await player.getPlaylistIndex() ``` -------------------------------- ### Initialize YouTubePlayer Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/README.md Create an instance of the YouTubePlayer class with a specified video source, parameters, and configuration. ```swift let player = YouTubePlayer( source: .video(id: "psL_5RIBqnY"), parameters: .init(autoPlay: true), configuration: .init() ) ``` -------------------------------- ### Tracking Playback Progress with a Custom Class Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/11-Events-And-Observing.md Implement a custom ObservableObject class to track playback progress. This involves monitoring the .playing state to record start and end times and accumulating watch time. Ensure proper initialization and subscription to the player's publishers. ```swift class PlaybackTracker: ObservableObject { @Published var startTime: Date? @Published var endTime: Date? @Published var totalWatchTime: TimeInterval = 0 let player: YouTubePlayer private var cancellables = Set() init(player: YouTubePlayer) { self.player = player setupTracking() } private func setupTracking() { player.playbackStatePublisher .sink { [weak self] state in if state == .playing { self?.startTime = Date() } else if let startTime = self?.startTime { self?.totalWatchTime += Date().timeIntervalSince(startTime) self?.startTime = nil } } .store(in: &cancellables) } } ``` -------------------------------- ### Initialize YouTubePlayer.Source with Channel Name Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/README.md Use this to specify a YouTube channel by its name. ```swift let channel: YouTubePlayer.Source = .channel(name: "GoogleDevelopers") ``` -------------------------------- ### getPlaylistIndex Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Gets the current 0-based index of the video playing within the playlist. ```APIDOC ## getPlaylistIndex ### Description Returns the current position in the playlist (0-based index). ### Method GET ### Endpoint /playlist/index ### Parameters #### Query Parameters None ### Response #### Success Response (200) - **index** (Int) - Current playlist index, or -1 if no playlist #### Response Example { "index": 1 } ``` -------------------------------- ### Initialize YouTubePlayer.Source with Multiple Video IDs Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/README.md Use this to specify a series of YouTube videos by their IDs. ```swift let videos: YouTubePlayer.Source = .videos(ids: ["w87fOAG8fjk", "RXeOiIDNNek", "psL_5RIBqnY"]) ``` -------------------------------- ### Get Current Playback Time Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Retrieves the current position of the video playback in seconds. ```swift func getCurrentTime() async throws(APIError) -> Double ``` ```swift let currentTime = try await youTubePlayer.getCurrentTime() print("Current time: \(currentTime)s") ``` -------------------------------- ### Get Available Playback Rates Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Retrieves an array of all playback rates that are available for the current video. ```swift func getAvailablePlaybackRates() async throws(APIError) -> [PlaybackRate] ``` ```swift let rates = try await youTubePlayer.getAvailablePlaybackRates() print("Available rates: \(rates)") ``` -------------------------------- ### Observe Playback Metadata Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/11-Events-And-Observing.md Get comprehensive video metadata, including title and author, by subscribing to the playbackMetadataPublisher. ```swift let cancellable = youTubePlayer .playbackMetadataPublisher .sink { print("Title: \(metadata.title ?? \"Unknown\")") print("Author: \(metadata.author ?? \"Unknown\")") } ``` -------------------------------- ### YouTubePlayer Initializers Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Initializers for creating a YouTubePlayer instance, including a default initializer with various options, and convenience initializers for creating players from URLs or URL strings. ```APIDOC ## YouTubePlayer Initializers ### Default Initializer ```swift nonisolated public init( source: Source? = nil, parameters: Parameters = .init(), configuration: Configuration = .init(), isLoggingEnabled: Bool = false ) ``` #### Parameters - **source** (`YouTubePlayer.Source?`) - The source to load - **parameters** (`YouTubePlayer.Parameters`) - Player parameters - **configuration** (`YouTubePlayer.Configuration`) - Web view configuration - **isLoggingEnabled** (Bool) - Enable OSLog output ### From URL ```swift nonisolated convenience init(url: URL) ``` #### Parameters - **url** (`URL`) - YouTube URL to parse ### From URL String ```swift nonisolated convenience init(urlString: String) ``` #### Parameters - **urlString** (String) - YouTube URL string to parse ### String Literal ```swift nonisolated convenience init(stringLiteral urlString: String) ``` Allows direct string assignment: `let player: YouTubePlayer = "https://youtube.com/watch?v=..."` ``` -------------------------------- ### Getting Thumbnails from Player Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md Retrieves thumbnail URLs or images directly from a currently playing YouTube video. ```APIDOC ## Getting Thumbnails from Player ### Description Retrieves thumbnail URLs or images directly from a currently playing YouTube video. ### Methods - `getVideoThumbnailURL(resolution: Resolution) async throws -> URL` - Retrieves the URL of the thumbnail for the currently playing video. - `getVideoThumbnailImage(resolution: Resolution) async throws -> YouTubeVideoThumbnail.Image` - Retrieves the image data of the thumbnail for the currently playing video. ### Parameters - **resolution** (Resolution) - The desired resolution for the thumbnail. ### Example ```swift // Get thumbnail URL let url = try await youTubePlayer.getVideoThumbnailURL(resolution: .maximum) // Get thumbnail image let image = try await youTubePlayer.getVideoThumbnailImage(resolution: .high) ``` ``` -------------------------------- ### YouTubePlayer.Source Initializers Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/08-Types-Reference.md Initializers for creating a YouTubePlayer.Source from a URL, URL string, or an array of video IDs. ```swift init?(url: URL) init?(urlString: String) init(arrayLiteral: String...) ``` -------------------------------- ### Get Video Duration Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Retrieves the total duration of the video in seconds. Returns 0 if the duration is unavailable. ```swift func getDuration() async throws(APIError) -> Double ``` ```swift let duration = try await youTubePlayer.getDuration() print("Duration: \(Int(duration))s") ``` -------------------------------- ### Initialize YouTubePlayer Parameters Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Create a set of parameters to control the YouTube player's behavior and appearance. These can be modified at runtime, but will cause the player to reload. ```swift let parameters = YouTubePlayer.Parameters( autoPlay: true, loopEnabled: false, startTime: .init(value: 30, unit: .seconds), endTime: .init(value: 120, unit: .seconds), showControls: true, showFullscreenButton: true, progressBarColor: .red, keyboardControlsDisabled: false, language: "en", captionLanguage: "en", showCaptions: false, restrictRelatedVideosToSameChannel: false ) ``` -------------------------------- ### Get Playlist ID Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves the ID of the currently loaded playlist. Use this to identify or reference the playlist. ```swift let playlistId = try await youTubePlayer.getPlaylistId() ``` -------------------------------- ### YouTubePlayer Initializer from URL Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Initializes a YouTubePlayer instance by parsing a given URL. This convenience initializer simplifies loading a video directly from a URL. ```swift nonisolated convenience init(url: URL) ``` -------------------------------- ### Get a Module Option Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Retrieves the value of a specific option from a player module. Requires a converter to process the response. ```swift func getModuleOption( module: Module, option: Option, converter: JavaScriptEvaluationResponseConverter ) async throws(APIError) -> Response ``` -------------------------------- ### Initialize YouTubeVideoThumbnail Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md Demonstrates different ways to initialize a YouTubeVideoThumbnail object, including using video ID, string literal, and URL. ```swift let thumbnail = YouTubeVideoThumbnail( videoID: "psL_5RIBqnY", resolution: .high ) let thumbnail2 = YouTubeVideoThumbnail("psL_5RIBqnY") // String literal if let thumbnail3 = YouTubeVideoThumbnail(url: url) { // Initialized from URL } ``` -------------------------------- ### Get Thumbnail Image from Player Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md Retrieves the thumbnail image of the currently playing YouTube video from the player instance. ```swift // Get thumbnail image let image = try await youTubePlayer.getVideoThumbnailImage( resolution: .high ) ``` -------------------------------- ### YouTubePlayer.Configuration Struct Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/08-Types-Reference.md Defines the web view and player configuration settings. Includes options for fullscreen, media playback, and data handling. ```swift public struct Configuration: Hashable, Sendable { public let fullscreenMode: FullscreenMode public let allowsInlineMediaPlayback: Bool public let allowsAirPlayForMediaPlayback: Bool public let allowsPictureInPictureMediaPlayback: Bool public let useNonPersistentWebsiteDataStore: Bool public let automaticallyAdjustsContentInsets: Bool public let customUserAgent: String? public let htmlBuilder: HTMLBuilder public let openURLAction: OpenURLAction } ``` -------------------------------- ### Get Thumbnail URL from Player Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md Retrieves the thumbnail URL of the currently playing YouTube video from the player instance. ```swift // Get thumbnail URL let url = try await youTubePlayer.getVideoThumbnailURL( resolution: .maximum ) ``` -------------------------------- ### Get Thumbnail URL Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md Retrieves the URL for a YouTube video thumbnail based on its video ID and desired resolution. ```swift let thumbnail = YouTubeVideoThumbnail( videoID: "psL_5RIBqnY", resolution: .high ) if let url = thumbnail.url { print("Thumbnail URL: \(url)") // https://img.youtube.com/vi/psL_5RIBqnY/hqdefault.jpg } ``` -------------------------------- ### Get Current Volume Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/04-Volume-And-Mute-API.md Retrieves the current volume level of the YouTube player. The volume is an integer between 0 and 100. ```swift func getVolume() async throws(APIError) -> Int ``` ```swift let volume = try await youTubePlayer.getVolume() print("Volume: \(volume)%") ``` -------------------------------- ### Get Video Statistics Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves comprehensive statistics for the current video, including impression counts and engagement metrics. ```swift let stats = try await youTubePlayer.getVideoStats() ``` -------------------------------- ### Example: Reload Captions Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Reloads the caption data for the player. This can be useful after making changes to caption settings or tracks. ```swift try await youTubePlayer.setModuleOption( module: .captions, option: .reload, value: true ) ``` -------------------------------- ### YouTubePlayer Initializer from URL String Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Initializes a YouTubePlayer instance by parsing a YouTube URL provided as a string. This is a convenient way to load videos when you have the URL as text. ```swift nonisolated convenience init(urlString: String) ``` -------------------------------- ### Time Range Clipping Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Define a specific time range for video playback, playing only between the specified start and end times. ```swift let parameters = YouTubePlayer.Parameters( startTime: .init(value: 30, unit: .seconds), endTime: .init(value: 120, unit: .seconds) ) // Plays only seconds 30-120 of the video ``` -------------------------------- ### Initialize YouTubePlayer.Source with Playlist ID Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/README.md Use this to specify a YouTube playlist by its ID. ```swift let playlist: YouTubePlayer.Source = .playlist(id: "PLHFlHpPjgk72Si7r1kLGt1_aD3aJDu092") ``` -------------------------------- ### Get Playlist Size Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/06-Playlist-Queue-API.md Retrieves the total number of videos in the currently loaded playlist. This function requires a playlist to be loaded. ```swift func getPlaylistSize() async throws(APIError) -> Int ``` ```swift let size = try await youTubePlayer.getPlaylistSize() print("Playlist has \(size) videos") ``` -------------------------------- ### YouTubePlayer Default Initializer Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/01-YouTube-Player.md Initializes a new YouTubePlayer instance with optional source, parameters, configuration, and logging settings. All parameters have default values. ```swift nonisolated public init( source: Source? = nil, parameters: Parameters = .init(), configuration: Configuration = .init(), isLoggingEnabled: Bool = false ) ``` -------------------------------- ### YouTubePlayerHostingView Programmatic Layout Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/07-UI-Components.md Demonstrates programmatic layout of a YouTubePlayerHostingView within a UIKit view. The player is initialized with a URL, and constraints are applied to position and size the view, maintaining a 9:16 aspect ratio. ```swift import UIKit import YouTubePlayerKit let player: YouTubePlayer = "https://youtube.com/watch?v=psL_5RIBqnY" let playerView = YouTubePlayerHostingView(player: player) view.addSubview(playerView) playerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ playerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), playerView.heightAnchor.constraint(equalTo: playerView.widthAnchor, multiplier: 9/16) ]) ``` -------------------------------- ### Get Playback Rate Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Retrieves the current playback speed of the video. Values range from 0.25x (slow) to 2.0x (fast). ```swift func getPlaybackRate() async throws(APIError) -> PlaybackRate ``` ```swift let rate = try await youTubePlayer.getPlaybackRate() print("Playback rate: \(rate)") ``` -------------------------------- ### getPlaybackRate Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/02-Playback-API.md Returns the current playback speed of the video. For example, 1.0 is normal speed, 0.25 is slow, and 2.0 is fast. ```APIDOC ## getPlaybackRate ### Description Returns the current playback speed (1.0 = normal, 0.25 = slow, 2.0 = fast). ### Method Asynchronous function call ### Returns - **YouTubePlayer.PlaybackRate** - Current playback rate ### Throws - **YouTubePlayer.APIError** - On evaluation failure ### Example ```swift let rate = try await youTubePlayer.getPlaybackRate() print("Playback rate: \(rate)") ``` ``` -------------------------------- ### Extend with Custom Modules Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/13-Module-API.md Demonstrates how to extend the YouTubePlayer.Module and YouTubePlayer.Module.Option enums to support custom modules and options beyond the built-in ones. This is useful for integrating custom player functionalities. ```swift public extension YouTubePlayer.Module { // Custom modules can be added here static let customModule = Module(rawValue: "customModule") } public extension YouTubePlayer.Module.Option { // Custom options per module static let customOption = Option(rawValue: "customOption") } ``` -------------------------------- ### Get Combined Volume State Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/04-Volume-And-Mute-API.md Retrieves both the current volume level and mute status in a single call. Returns a `VolumeState` struct. ```swift func getVolumeState() async throws(APIError) -> VolumeState ``` ```swift let state = try await youTubePlayer.getVolumeState() print("Volume: \(state.volume)%, Muted: \(state.isMuted)") ``` -------------------------------- ### Define Preferred Fullscreen Mode Based on Platform Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/09-Configuration-Guide.md Create a static property to determine the preferred fullscreen mode based on the operating system. Uses .web for macOS and visionOS, and .system for others. ```swift extension YouTubePlayer.FullscreenMode { static let preferred: Self = { #if os(macOS) || os(visionOS) return .web #else return .system #endif }() } ``` -------------------------------- ### Get Video Thumbnail Image Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves the actual thumbnail image data for the video. Allows specifying resolution, defaulting to .standard. ```swift let image = try await youTubePlayer.getVideoThumbnailImage(resolution: .maximum) imageView.image = image ``` -------------------------------- ### Load Thumbnail Image with Async/Await Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/12-Video-Thumbnail-API.md Asynchronously loads the thumbnail image for a given video ID and resolution using async/await. ```swift func getThumbnailImage() async throws -> YouTubeVideoThumbnail.Image { let thumbnail = YouTubeVideoThumbnail( videoID: "psL_5RIBqnY", resolution: .maximum ) return try await thumbnail.image() } ``` -------------------------------- ### Get Video Thumbnail URL Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves the URL for the video's thumbnail image. Allows specifying resolution, defaulting to .standard. ```swift let url = try await youTubePlayer.getVideoThumbnailURL(resolution: .maximum) print("Thumbnail: \(url)") ``` -------------------------------- ### Get Playlist Index Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves the 0-based index of the currently playing video within the playlist. Returns -1 if no playlist is loaded. ```swift let index = try await youTubePlayer.getPlaylistIndex() print("Playing video \(index) of playlist") ``` -------------------------------- ### Initialize YouTubePlayer.Source with Video ID Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/README.md Use this to specify a single YouTube video source by its ID. ```swift let video: YouTubePlayer.Source = .video(id: "psL_5RIBqnY") ``` -------------------------------- ### Loading YouTube Content from URL Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/00-Index.md Initialize the YouTubePlayer by providing a YouTube URL or parsing a video ID from a URL. This is the primary method for loading video content. ```swift // From YouTube URL let player = YouTubePlayer(urlString: "https://youtube.com/watch?v=psL_5RIBqnY") // Parse video ID from URL if let source = YouTubePlayer.Source(urlString: urlString) { player.source = source } ``` -------------------------------- ### Get Video Embed Code Source: https://github.com/sventiigi/youtubeplayerkit/blob/main/_autodocs/03-Video-Information-API.md Retrieves the HTML embed code for the current video. This is useful for embedding the video in web pages. ```swift let embedCode = try await youTubePlayer.getVideoEmbedCode() //