Autoplay YouTube videos in WKWebView with iOS 11

前端 未结 5 894
小鲜肉
小鲜肉 2020-12-17 17:19

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

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 17:32

    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);

提交回复
热议问题