3

I have given size of WKWebView("myPlayer" in below code) frame dynamically for the iFrame embedded in it but the youtube video view displays 1/3 of WKWebView. Below is my code and reference image.

small video in WKWebView

let videoURL:URL = URL(string: "https://www.youtube.com/embed/695PN9xaEhs")!
@IBOutlet weak var myPlayer: WKWebView!
var didLoadVideo = false
var embedVideoHtml:String?
override func viewDidLoad() {
    super.viewDidLoad()
    embedVideoHtml = {
    return """
    <!DOCTYPE html>
    <html>
    <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
    function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
    playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
    height: '\(myPlayer.frame.height)',
    width: '\(myPlayer.frame.width)',
    videoId: '\(videoURL.lastPathComponent)',
    events: {
    'onReady': onPlayerReady
    }
    });
    }

    function onPlayerReady(event) {
    event.target.playVideo();
    }
    </script>
    </body>
    </html>
    """
}()


}

So any one have idea how to fit the youtube video view in myPlayer frame?

Manish
  • 608
  • 1
  • 11
  • 23
  • Try printing the embedVideoHtml and see if the values are being set properly – AjinkyaSharma Apr 11 '19 at 10:38
  • @AjinkyaSharma the embedVideoHtml shows same size(width, height) of WKWebView but does not fit into it. I think there must be scaling issue..as there is concept of px. what do you think? – Manish Apr 11 '19 at 11:14
  • I had a similar issue to this trying to embed a Vimeo video. For me, setting width and height to 100% didn't help, but this answer did: https://stackoverflow.com/a/58664524/4397 – andygeers Sep 17 '20 at 12:13

1 Answers1

6

In your embedVideoHtml before <body> add the following code:

<style>
    * { margin: 0; padding: 0; }
    html, body { width: 100%; height: 100%; }
</style>

and in the player parameters change the following parameters:

height: '\(myPlayer.frame.height)',
width: '\(myPlayer.frame.width)',

to:

height: '100%',
width: '100%',

After these changes your player should be adjusted to the size of WKWebView

axel
  • 422
  • 2
  • 14