Search code examples
iosswiftuiwebviewios9

Youtube video embedded in UIWebView has no sound on real device


This is how I embed my video. It has sound in the simulator, however has no sound on a real device (iOS 9.0.2 (13A452)) Xcode 7.1.1.

This is the code I use to play it:

if let youtubeID = youtubeID {
    let embededHTML = "<html><body><iframe src=\"http://www.youtube.com/embed/\(youtubeID)?playsinline=1\" width=\"\(width)\" height=\"\(height)\" frameborder=\"0\" allowfullscreen></iframe></body></html>"
    cell!.webView.allowsInlineMediaPlayback = true
    cell!.webView.scalesPageToFit = true
    cell!.webView.mediaPlaybackAllowsAirPlay = true
    cell!.webView.mediaPlaybackRequiresUserAction = false

    cell!.webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().bundleURL)
}

Solution

  • I found the answer myself: Here the solution:

            if let youtubeID = youtubeID {
                let embededHTML = "<!DOCTYPE html><html><head><style type=\"text/css\"> body { margin: 0; padding: 0; } body, html { height: 100%; width: 100%; } </style> </head> <body> <iframe id=\"player\" type=\"text/html\" width=\"100%\" height=\"100%\" src=\"http://www.youtube.com/embed/\(youtubeID)?enablejsapi=1&playsinline=1\" frameborder=\"0\"></iframe> <script> var tag = document.createElement('script'); tag.src = \"https://www.youtube.com/iframe_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body></html>"
    
                cell!.webView.allowsInlineMediaPlayback = true
                cell!.webView.scalesPageToFit = true
                cell!.webView.mediaPlaybackAllowsAirPlay = true
                cell!.webView.mediaPlaybackRequiresUserAction = false
                cell!.webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().bundleURL)
            }