I want to have small YouTube player in my app. The only way i found to be recommended is embeding web page with YouTube player into my app. So i used WKWebView and loaded em
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 = $"";
_wkYoutubePlayer.LoadHtmlString(html, null);