Skip to content

Instantly share code, notes, and snippets.

@Pobe16
Last active May 24, 2022 21:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Pobe16/a1d7d035371de87a74340fad692a8881 to your computer and use it in GitHub Desktop.
Save Pobe16/a1d7d035371de87a74340fad692a8881 to your computer and use it in GitHub Desktop.
YouTubeView UIViewRepresentable
import SwiftUI
import UIKit
import YouTubePlayer
final class YouTubeView: UIViewRepresentable {
typealias UIViewType = YouTubePlayerView
@ObservedObject var playerState: YouTubeControlState
init(playerState: YouTubeControlState) {
self.playerState = playerState
}
func makeCoordinator() -> Coordinator {
Coordinator(playerState: playerState)
}
func makeUIView(context: Context) -> UIViewType {
let playerVars = [
"controls": "1",
"playsinline": "0",
"autohide": "0",
"autoplay": "0",
"fs": "1",
"rel": "0",
"loop": "0",
"enablejsapi": "1",
"modestbranding": "1"
]
let ytVideo = YouTubePlayerView()
ytVideo.playerVars = playerVars as YouTubePlayerView.YouTubePlayerParameters
ytVideo.delegate = context.coordinator
return ytVideo
}
func updateUIView(_ uiView: UIViewType, context: Context) {
guard let videoID = playerState.videoID else { return }
if !(playerState.executeCommand == .idle) && uiView.ready {
switch playerState.executeCommand {
case .loadNewVideo:
playerState.executeCommand = .idle
uiView.loadVideoID(videoID)
case .play:
playerState.executeCommand = .idle
uiView.play()
case .pause:
playerState.executeCommand = .idle
uiView.pause()
case .forward:
playerState.executeCommand = .idle
uiView.getCurrentTime { (time) in
guard let time = time else {return}
uiView.seekTo(Float(time) + 10, seekAhead: true)
}
case .backward:
playerState.executeCommand = .idle
uiView.getCurrentTime { (time) in
guard let time = time else {return}
uiView.seekTo(Float(time) - 10, seekAhead: true)
}
default:
playerState.executeCommand = .idle
print("\(playerState.executeCommand) not yet implemented")
}
} else if !uiView.ready {
uiView.loadVideoID(videoID)
}
}
class Coordinator: YouTubePlayerDelegate {
@ObservedObject var playerState: YouTubeControlState
init(playerState: YouTubeControlState) {
self.playerState = playerState
}
func playerReady(_ videoPlayer: YouTubePlayerView) {
videoPlayer.play()
playerState.videoState = .play
}
func playerStateChanged(_ videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) {
switch playerState {
case .Playing:
self.playerState.videoState = .play
case .Paused, .Buffering, .Unstarted:
self.playerState.videoState = .pause
case .Ended:
self.playerState.videoState = .stop
self.playerState.videoID = loadNextVideo()
default:
print("\(playerState) not implemented")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment