This content originally appeared on DEV Community and was authored by Fathima A
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
}
}
This content originally appeared on DEV Community and was authored by Fathima A
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
Fathima A | Sciencx (2025-01-22T06:29:53+00:00) Creating a Custom YouTube Player in SwiftUI Using WKWebView. Retrieved from https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/
" » Creating a Custom YouTube Player in SwiftUI Using WKWebView." Fathima A | Sciencx - Wednesday January 22, 2025, https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/
HARVARDFathima A | Sciencx Wednesday January 22, 2025 » Creating a Custom YouTube Player in SwiftUI Using WKWebView., viewed ,<https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/>
VANCOUVERFathima A | Sciencx - » Creating a Custom YouTube Player in SwiftUI Using WKWebView. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/
CHICAGO" » Creating a Custom YouTube Player in SwiftUI Using WKWebView." Fathima A | Sciencx - Accessed . https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/
IEEE" » Creating a Custom YouTube Player in SwiftUI Using WKWebView." Fathima A | Sciencx [Online]. Available: https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/. [Accessed: ]
rf:citation » Creating a Custom YouTube Player in SwiftUI Using WKWebView | Fathima A | Sciencx | https://www.scien.cx/2025/01/22/creating-a-custom-youtube-player-in-swiftui-using-wkwebview/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.