It’s not possible to use AVKit to play YouTube videos directly, so we need to use a different solution: a Web View from WebKit.
First, we need to analyze the YouTube URL. For example:
“https://www.youtube.com/watch?v=ZJmn2RCtFLQ“
We need to extract the video ID, which is the string after v= — in this case, ZJmn2RCtFLQ.
Since we don’t want to display the entire YouTube page, we can use the embed option to show only the video:
“https://www.youtube.com/embed/ZJmn2RCtFLQ“
Now, let’s take a look at the code:
import SwiftUI
import WebKit
struct YoutubePlayer: UIViewRepresentable {
let webView = WKWebView()
let videoUrl: String
public func makeUIView(context: Context) -> some UIView {
webView
}
public func updateUIView(_ uiView: UIViewType, context: Context) {
guard let url = URL(string: videoUrl) else { return }
let request = URLRequest(url: url)
webView.load(request)
}
}The makeView function returns a WebView, while the updateView function loads the page specified by the videoUrl.
To use it:
struct YoutubeUIView: View {
var body: some View {
YoutubePlayer(videoUrl: "https://www.youtube.com/embed/ZJmn2RCtFLQ")
.aspectRatio(4/3, contentMode: .fit)
}
}For the aspect ratio, we chose 4:3, but feel free to use 16:9 or remove it altogether to use the default settings.
Thus, we have:
