DEV Community

Fathima A
Fathima A

Posted on

Creating a Custom YouTube Player in SwiftUI Using WKWebView

import SwiftUI
import WebKit

/**
 `YouTubePlayerView` is a SwiftUI view that embeds a YouTube video player using a `WKWebView`.

 This view takes a YouTube video URL and loads it in a `WKWebView` to play the video. It supports both the standard YouTube "watch" URLs (`https://www.youtube.com/watch?v=...`) and the "embed" URLs (`https://www.youtube.com/embed/...`). The view automatically converts a "watch" URL into an "embed" URL, ensuring the video is displayed properly.

 Key features include:
 - Supports inline media playback for YouTube videos.
 - Automatically handles autoplay for videos.
 - Supports AirPlay for video playback.
 - Maintains the correct 16:9 aspect ratio for video display.
 - Disables scrolling within the `WKWebView` for a clean video player interface.

 This view is ideal for embedding YouTube videos within a SwiftUI application, ensuring a seamless user experience with minimal configuration.
 */``
struct YouTubePlayerView: UIViewRepresentable {
    let videoURL: String  // The URL of the YouTube video to display.

    /// Creates and returns a WKWebView configured for YouTube playback.
    func makeUIView(context: Context) -> WKWebView {
        // Configure web page preferences to allow JavaScript content
        let preferences = WKWebpagePreferences()
        preferences.allowsContentJavaScript = true

        // Set up WKWebView configuration with necessary preferences
        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences = preferences
        config.allowsInlineMediaPlayback = true  // Allow inline video playback
        config.mediaTypesRequiringUserActionForPlayback = .all  // Allow autoplay
        config.allowsAirPlayForMediaPlayback = true  // Enable AirPlay for media playback

        // Initialize the WKWebView with the custom configuration
        let webView = WKWebView(frame: .zero, configuration: config)
        webView.scrollView.isScrollEnabled = false  // Disable scrolling inside the player

        // Maintain the correct aspect ratio for the video (16:9)
        webView.translatesAutoresizingMaskIntoConstraints = false
        return webView
    }

    /// Updates the WKWebView with a new video URL.
    func updateUIView(_ uiView: WKWebView, context: Context) {
        print(videoURL)  // Log the current video URL for debugging

        // Initialize the embed URL as an empty string
        var embedURL: String

        // Check if the provided URL is a standard YouTube 'watch' URL
        if videoURL.contains("youtube.com/watch") {
            // Extract the video ID from the 'watch' URL
            guard let videoID = videoURL.split(separator: "=").last else { return }
            // Construct the embed URL using the extracted video ID
            embedURL = "https://www.youtube.com/embed/\(videoID)"
        } else {
            // If the URL is already in embed format, use it directly
            embedURL = videoURL
        }

        // Convert the embed URL into a URL object and load it in the web view
        guard let url = URL(string: embedURL) else { return }
        let request = URLRequest(url: url)
        uiView.load(request)  // Load the YouTube video in the WKWebView
    }
}
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools