0
votes

I am using WebView for playing video in my Xamarin.Forms project. On iPhone the video is playing in fullscreen, but I need to play the video within the WebView without going to fullscreen.

I have this issue only on the iPhone. On Android, Windows, and iPad devices the video is playing without fullscreen.

Case 1: Normal WebView

<WebView 
    x:Name="web_view"
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand"/>

web_view.Source = videoUrl;

Case 2: Custom webview

On some part, I am using a custom WebView. In this case the video is also being played in full-screen mode.

public  class MyWebView : WebView
{
    public static readonly BindableProperty UrlProperty = BindableProperty.Create(
    propertyName: "Url",
    returnType: typeof(string),
    declaringType: typeof(MyWebView),
    defaultValue: default(string));

    public string Url
    {
        get { return (string)GetValue(UrlProperty); }
        set { SetValue(UrlProperty, value); }
    }
}

In the above 2 cases, I need to play the video without full-screen mode on the iPhone.

1

1 Answers

0
votes

You could set AllowsInlineMediaPlayback as True in Custom Renderer

[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]

namespace CustomWebview.iOS
{
    public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
    {
        WKWebView wkWebView;

        protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                WKWebViewConfiguration configuration = new WKWebViewConfiguration();
                configuration.AllowsInlineMediaPlayback = true;
                wkWebView = new WKWebView(CGRect.Empty, configuration);

                if (Element.Url != null)
                {
                    wkWebView.LoadRequest(new NSUrlRequest(new NSUrl((Element).Url)));
                }
                SetNativeControl(wkWebView);
            }

            if (e.NewElement != null)
            {
                CallVideo();
            }
        }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals(nameof(Element.Url)))
            {
                wkWebView.LoadRequest(new NSUrlRequest(new NSUrl((Element).Url)));
            }
        }

        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            Control.Frame = rect;
        }
    }
}

Added an if statement to exclude the null condition. And then load the URL when you set it in Forms. OnElementPropertyChanged will be called when the property of webview has been changed. So when you set its URL in forms, we could load requests in this method.