When trying to show youtube video in my app with embeded way, it shows the error code: 152 - 4.
I just want to make a view where passing the YouTube ID will play the YouTube video inside my app's specific screens/views. Now this error occurs when trying to play the video.

Any workaround on this? I can not find any so far.

My code:

final class YouTubePlayerViewController: UIViewController, WKNavigationDelegate { var youtubeId: String private var webView: WKWebView! init(youtubeId: String) { self.youtubeId = youtubeId super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black setupWebView() loadPlayer() } private func setupWebView() { let config = WKWebViewConfiguration() config.allowsInlineMediaPlayback = true config.allowsAirPlayForMediaPlayback = true config.allowsPictureInPictureMediaPlayback = true config.mediaTypesRequiringUserActionForPlayback = [] // Required — tells WKWebView it is allowed to autoplay / inline play let prefs = WKWebpagePreferences() prefs.allowsContentJavaScript = true config.defaultWebpagePreferences = prefs webView = WKWebView(frame: view.bounds, configuration: config) webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] webView.navigationDelegate = self webView.scrollView.isScrollEnabled = false webView.scrollView.bounces = false webView.backgroundColor = .black webView.isOpaque = true view.addSubview(webView) } func loadPlayer() { // The critical trick: we load a real youtube.com URL as the *base* // and inject an autoplay embed via HTML. Because the base URL is // genuinely youtube.com, WKWebView passes YouTube's origin check. let html = """ <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <style> html, body { margin: 0; padding: 0; background: #000; width: 100%; height: 100%; overflow: hidden; } iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; } </style> </head> <body> <iframe src="https://www.youtube.com/embed/\(youtubeId)?playsinline=1&rel=0&modestbranding=1&autoplay=0&controls=1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen> </iframe> </body> </html> """ // baseURL MUST be a real youtube.com origin — this is what fixes Error 152 webView.loadHTMLString(html, baseURL: URL(string: "https://www.youtube.com")) } func updateYoutubeId(_ newId: String) { guard newId != youtubeId else { return } youtubeId = newId loadPlayer() } }

d0tb0t's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.