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?
If you are only interested in telephone devices, then the technique mentioned here might be useful to you: Determine iPhone user's country
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.Here's an alternative, perhaps overly circuitous method. The other solutions are based on manual settings (NSLocale) or on requesting for permission to use location services which can be denied (CLLocationManager), so they have drawbacks.
You can get the current country based on the local timezone. My app is interfacing with a server running Python with pytz installed, and that module provides a dictionary of country codes to timezone strings. I only really need to have the server know the country so I don't have to set it up entirely on iOS. On the Python side:
On the iOS side:
I have my server send in the local timezone name and look it up in the pytz country_timezones dictionary.
If you make an iOS version of the dictionary available in pytz or some other source, you can use it to immediately look up the country code without the help of a server, based on timezone settings, which are often up to date.
I may be misunderstanding NSLocale though. Does it give you the country code through regional formatting preferences or timezone settings? If the latter, then this is just a more complicated way of getting the same result...
Here's a quick loop in Swift 3 that returns a complete list of country codes.
@Denis's answer is good -- here is some code putting his answer into practice. This is for a custom class that you have set to conform to the
CLLocationManagerDelegate
protocol. It's a little simplified (e.g. if the location manager returns multiple locations, it just goes with the first one) but should give folks a decent start...For Swift 3 it's even simpler: