question

JassimAlRahma-9056 avatar image
0 Votes"
JassimAlRahma-9056 asked JarvanZhang-MSFT commented

Determine User Location

Hi,

ia m trying to determine the user location so that. can redirect to the store page based on his location (which is the country or state)

I know it can be done with Xamarin Essentials but what if he did not grant the access?

i though of getting the location from his IP.

I tried below code:

 private string GetLocalAddress()
 {
     var host = Dns.GetHostEntry(Dns.GetHostName());
     foreach (var ip in host.AddressList)
     {
         if (ip.AddressFamily == AddressFamily.InterNetwork)
         {
             return ip.ToString();
         }
     }
    
     throw new Exception("Local IP Address Not Found!");
 }


but getting:

System.Net.Sockets.SocketException: Could not resolve host 'iPhone'


Kindly advise..

dotnet-csharpdotnet-xamarindotnet-runtimedotnet-standard
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

How are you testing? A phone has an IP address if it is on a network not through cell service.

0 Votes 0 ·

I am testing on iPhone (data) and (WiFi)

0 Votes 0 ·

can redirect to the store page based on his location (which is the country or state)

Hi, JassimAlRahma-9056. I tested the code in a basic sample, it works fine. There is not exception occured. You can create a specialized storage category for some users who don't want to provide location permissions. To protect user privacy, apps that use location services must request location permissions. We should not try to get the location without granting the permission.

0 Votes 0 ·

1 Answer

Castorix31 avatar image
0 Votes"
Castorix31 answered

The method : Get the user's location works for me (Windows 10, VS 2019)
(test in a Winforms app, without "location capability", I get GeolocationAccessStatus.Allowed and the right location
with Geoposition pos = await geolocator.GetGeopositionAsync();)




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.