Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get device location (only country) in iOS

I need to get the country location of a iOS device.

I've been trying to use CoreLocation with MKReverseGeocoder. However this seems to return erraneous quite frequently. And I only need the country, no need for streets and such.

How can this be done in a more stable way?

like image 629
johan Avatar asked Dec 16 '11 12:12

johan


People also ask

How can I get current country code in IOS?

To find the country of the user's chosen language: NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale. NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode]; // get country code, e.g. ES (Spain), FR (France), etc.

What is Cllocationmanager in Swift?

The object that you use to start and stop the delivery of location-related events to your app.


2 Answers

NSString *countryCode = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode]; 

will get you an identifier like e.g. "US" (United States), "ES" (Spain), etc.


In Swift 3:

let countryCode = NSLocale.current.regionCode 

In Swift 2.2:

let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as String 

Compared to a solution based on CLLocationManager this approach has pros and cons. The primary con is that it doesn't guarantee that this is where the device is physically if the user configures it differently. This can however also be seen as a pro since it instead shows which country a user is mentally/culturally aligned with - so if e.g. I go abroad on vacation then the locale is still set to my home country. However a pretty big pro is that this API doesn't require user permission like CLLocationManager does. So if you haven't already gotten permission to use the user's location, and you can't really justify throwing a popup dialog in the user's face (or they already rejected that popup and you need a fallback) then this is probably the API you want to use. Some typical use cases for this could be personalization (e.g. culturally relevant content, default formats, etc.) and analytics.

like image 83
Martin Gjaldbaek Avatar answered Oct 01 '22 10:10

Martin Gjaldbaek


NSLocale is just a setting about currently used regional settings, it doesn't mean the actual country you're in.

Use CLLocationManager to get current location & CLGeocoder to perform reverse-geocoding. You can get country name from there.

like image 20
Denis Avatar answered Oct 01 '22 10:10

Denis