Xamarin Version
-This can be added in view did load (hard-coding height). I also added "rel" for playerVars to only show related videos of my channel.
The WKWebview is created dynamically and added to a container. The idea was for the iframe to fill the WKWebView and the WKWebView to fill the container. I could never set the height to 100% so it scaled depending of the device but seems that a hard-coded 640 height works well for most devices.
I'm also passing the youtube id directly in a variable which is basically what videoURL.lastPathComponent returns.
Auto-play works fine which is the main solution for this thread.
var wkWebConfig = UIDevice.CurrentDevice.CheckSystemVersion(10, 0)
? new WKWebViewConfiguration
{
MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None
}
: new WKWebViewConfiguration
{
MediaPlaybackRequiresUserAction = false
};
_wkYoutubePlayer = new WKWebView(new CGRect(), wkWebConfig)
{
AccessibilityIdentifier = "viewPlayerYouTube",
TranslatesAutoresizingMaskIntoConstraints = false
};
viewPlayerContainerYouTube.AddSubview(_wkYoutubePlayer);
NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Top, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Top, 1, 0).Active = true;
NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Leading, 1, 0).Active = true;
NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Trailing, 1, 0).Active = true;
NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Bottom, 1, 0).Active = true;
var html = $"<!DOCTYPE html><html><body><div id=\"player\"></div><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', {{ height: '640', width: '100%', videoId: '{_youtubeVideoId}', playerVars: {{ rel: '0' }}, events: {{ 'onReady': onPlayerReady }} }}); }} function onPlayerReady(event) {{ event.target.playVideo(); }}</script></body></html>";
_wkYoutubePlayer.LoadHtmlString(html, null);