Home > Software design >  Repeated dialog box for permission access in Xamarin project - only in ios
Repeated dialog box for permission access in Xamarin project - only in ios

Time:12-13

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??

CodePudding user response:

You said the popup with the message: "website... Would Like To Use Your Current Location. Don't Allow / OK", but there is not Always option in this option. You can check how your WkWebViewRenderer is to request location permissions and you can use the requestAlwaysAuthorization method to obtain Always authorization. You also need to check whether the following keys have been added to your Info.plist file: NSLocationAlwaysUsageDescription, NSLocationWhenInUseUsageDescription, or NSLocationAlwaysAndWhenInUseUsageDescription.

For more details, you can refer to the following documents:

Background Location in Xamarin.iOS | Microsof

Requesting authorization to use location services | Apple Developer

CodePudding user response:

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

If you find this answer helpful, please upvote my answer.

  • Related