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 = """
https://www.youtube.com/watch?v=\(youtubeId)
"""
// baseURL MUST be a real youtube.com origin — this is what fixes Error 152
webView.loadHTMLString(html, baseURL: URL(string: "
}
func updateYoutubeId(_ newId: String) {
guard newId != youtubeId else { return }
youtubeId = newId
loadPlayer()
}
}