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

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay