Search code examples
xamarinxamarin.formsxamarin.iosprismwkwebview

Repeated dialog box for permission access in Xamarin project - only in ios


I have a Xamarin Prism Forms app that contains web page which should get the users current location. The app already has the required "app" permissions for Android. But in ios when I call my external web page it repeatedly shows me the popup with the message :"website... Would Like To Use Your Current Location. Don't Allow / OK" each time they visit the web page from inside my Xamarin app. I am using WkWebViewRenderer for webview.I have tried all the possible answers I got and still the problem persists.

Can anybody help me on this??


Solution

  • I found out the solution in How to prevent WKWebView to repeatedly ask for permission to access location?

    The steps I followed to solve the issue are:

    • Add the following code inside class definition:

      const string JavaScriptFunction = "navigator.geolocation.getCurrentPosition = function(success, error, options) {window.webkit.messageHandlers.locationHandler.postMessage('getCurrentPosition');};";
      
    • Add the following inside HybridWebViewRenderer constructor:

      var script = new WKUserScript(new NSString(JavaScriptFunction), 
                   WKUserScriptInjectionTime.AtDocumentStart, true);
      userController.AddUserScript(script);
      userController.AddScriptMessageHandler(this, "locationHandler");
      
    • Add the following in DidReceiveScriptMessage function:

      if (message.Name == "locationHandler")
      {
        var messageBody = message.Body.ToString();
        if (messageBody == "getCurrentPosition")
        {
          CLLocationManager manager=new CLLocationManager();
          manager.RequestAlwaysAuthorization();
          manager.StartUpdatingLocation();
          ((HybridWebView)Element).EvaluateJavaScriptAsync("getLocation(\" 
          (manager.location?.coordinate.latitude ?? 0) ,\" 
          (manager.location?.coordinate.longitude ?? 0))");
        }
      }