Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it determined when to prompt user location permissions on iOS safari?

When using the geolocation.getCurrentPosition API on mobile, tested iOS at the moment, users are prompted more than once through a session depending on the page. In comparison to as desktop site, such as Chrome on Windows 10, where once a user hits Allow they will no longer be prompted for permissions unless explicitly disabled. iOS Safari seems to be session based and then possibly page based within session?

Wondering if anyone knows if there are explicit rules defined by Apple for this permission check? Also does maximumAge play a role in how often the user is prompted?

  const LOCATION_OPTIONS = {
   timeout: 15000,
   enableHighAccuracy: true,
   maximumAge: 86400000,
  };

  useEffect(() => {
    const { geolocation } = navigator;

    // If the geolocation is not defined in the used browser we handle it as an error
    if (!geolocation) {
      setError("Geolocation is not supported.");
      return;
    }

    // Call Geolocation API
    geolocation.getCurrentPosition(handleSuccess, handleError, options);
  }, [options]);

  return { location, error };

Example NextJS CodeSandbox https://u11vn.sse.codesandbox.io/

like image 917
BillPull Avatar asked Dec 04 '21 18:12

BillPull


People also ask

Why does Safari always ask for my location?

Websites in Safari often bug you to let them access your location services to detect where you are. You can turn off those prompts on iPhone and iPad and even prevent the browser from accessing location services altogether.

How do you get Safari to ask your location?

Location Access in Safari iOS/iPadOSOpen the Privacy menu and choose the Location Services sub-menu. Enable the Location Services toggle. Scroll down on the Location Services page, and select the Safari app from the list. Choose the appropriate desired option from – Never, Ask Next Time, or While Using the App.

What does location permission do?

Important: If an app has permission to use your phone's location, it can use your phone's approximate location, precise location, or both.

How do I ask for location permissions in iOS?

It's important to take great care with a user's location data, and the system requires your app to get the user's authorization to access this kind of information. To request authorization, call requestWhenInUseAuthorization() or requestAlwaysAuthorization() , depending on the authorization status your app needs.


2 Answers

Unfortunately, it seems there is no way to permanently grant website access to the iPhone privacy like camera location, within Safari. but on the user side, there are three options (Ask, Allow, Deny ) that can set

if you use JavaScript in iOS WKWebView, you can get a workaround that request location with App location API

if you use JavaScript on the web, well you cannot achieve this.

like image 168
kun wang Avatar answered Sep 23 '22 00:09

kun wang


In the web do below / or use navigator with a popup dialog

 var options = {
  enableHighAccuracy: true,
  timeout: 7000,
  maximumAge: 0
};

function log(data) {
  const tag = document.createElement('p');
  tag.textContent = data;
  document.body.appendChild(tag);
}

function success(pos) {
  var crd = pos.coords;
  console.log('Successfully determined a user position:', crd);

  log('Your current position is:');
  log(`Latitude : ${crd.latitude}`);
  log(`Longitude: ${crd.longitude}`);
  log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

Or

$scope.watchId = navigator.geolocation.watchPosition(function (position) {
                        if ($scope.t1 == 0) {
                            $scope.t1 = position.timestamp;
                        } else {
                            if (Math.abs($scope.t1 - position.timestamp) > 5000) {
                                $scope.t1 = position.timestamp;
                                SellerRef.update({ Location: { Lat: position.coords.latitude, Long: position.coords.longitude } })
                            }
                        }
    
                    },
                        function (error) {
                            if (error.code == 1) {
                                  $scope.showAlert("An error occured \n" + " Please goto Settings->Privacy->LocationServices and give permission for " + bowser.name + " which is your browser ");
                            }
    
                        }
                    ); 

For loading your web inside an app

  • Then with webView, just add location permission descriptions to the info.plist file.
  • Add NSLocationWhenInUseUsageDescription versus NSLocationAlwaysUsageDescription versus NSLocationUsageDescription

What is the geolocation error, look here

navigator.geolocation.getCurrentPosition(success => {
  /* Do some magic. */
}, failure => {
  if (failure.message.startsWith("Only secure origins are allowed")) {
    // Secure Origin issue.
  }
});

Include/set an "required_features" option at manifest.webapp file:

{
  "required_features": ["geolocation"]
}

User:

On iPhone:

Settings -> Location Services -> [your Browser] [apple ref][1]

Chrome requires https for geolocation usage


Troubleshooting && Permissions Check / Debug Log

Check, user's OPERATING SYSTEM and BROWSER BOTH have location services enabled, user's browser supports checking for location services

    // options for current position
    const navigatorLocationOptions = {
      enableHighAccuracy: true,
      timeout: 7000,
      maximumAge: 0
    };
 
    // does browser have geo services enabled
    navigator.permissions.query({name:'geolocation'})
      .then((result) => {
        
        if (result.state === 'granted') {// you are good
          navigator.geolocation.getCurrentPosition(position => {
             console.log('granted user location permission', position );
              
             //.. do your stuff

          }, (error) => {
            // OS services are not enabled
            console.log('Please turn on OS located services', navigator);
            errorLocation();
          }, navigatorLocationOptions);

        } else {
          // browser issues seriveces
          console.log('Browser location services disabled', navigator);
          errorLocation();
        }
      }, (error) => {
        /* Browser doesn't support querying for permissions */
        console.log('Please turn on BROWSER location services', navigator);
        errorLocation()
      }
    );


    //handle errors
    function errorLocation() {
      ...
    }
like image 25
Transformer Avatar answered Sep 26 '22 00:09

Transformer