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

Top comments (0)