YouTube embedded video displaying wrong size

2019-09-15 08:52发布

问题:

I have embedded a youtube video in a UIWebView for display in my app.

Here's the code for that:

func loadVideo(){
    if let youtubeCode = exerciseYoutubeCode {
        guard !youtubeCode.isEmpty else { return }
        exerciseVideoWebView.isHidden = false
        exerciseVideoWebView.allowsInlineMediaPlayback = true
        exerciseVideoWebView.scrollView.isScrollEnabled = false
        exerciseVideoWebView.scrollView.bounces = false
        exerciseVideoWebView.loadHTMLString("<html><head><style>body{margin:0px}</style></head><body><iframe width=\"\(exerciseVideoWebView.frame.width)\" height=\"\(exerciseVideoWebView.frame.height)\" src=\"https://www.youtube.com/embed/\(youtubeCode)?&playsinline=1\" frameborder=\"0\" allowfullscreen></iframe></body></html>",
                                            baseURL: nil)
    }
}

The problem is that the embedded video does not seem to be respecting the width and height of the UIWebView that I am passing in to the iframe. In the simulator, the video is roughly 15-25 pixels larger than the UIWebView. I can live with that, but when running on a physical device, it's rendering 15-25 pixels smaller than the UIWebView, exposing the white of the HTML page on the right and bottom sides of the UIWebView.

The UIWebView has an AutoConstraint to a 16:9 ratio, which matches YouTube's video aspect ratio.

If I put the following script into the HTML, I can see that the width and height of the video iframe is an exact match to the height and width printed to the console for the UIWebView:

<script>setTimeout(function(){
    alert(document.getElementsByTagName('iframe')[0].offsetWidth + ' ' + document.getElementsByTagName('iframe')[0].offsetHeight)},10000)
</script>

Clearly there is some sort of scaling happening if the HTML thinks its the same size as the UIWebView, but I can't figure out how to fix it.