问题
This question is perhaps as much about human behaviour as programming.
What is the best way of automatically getting the user's country (without asking the user)
It's for a shopping app, so that the correct shopfront gets shown in the app. Imagine, for instance, there are three stores - Japan, US, and France.
There are three ways I can think of doing this:
- Use a service like http://ipinfo.io/json or http://freegeoip.net/json/ to get the country code.
- Use the device's carrier code, I'll be able to get the country where they registered their mobile phone.
- Use their phone's timezone - i.e., they've set their timezone to New York, so their country is US.
回答1:
I would have used the following:
NSString *locale = [[NSLocale currentLocale] localeIdentifier];
That will work for the vast majority of people who are in their own country, and haven't set their locale to some random other country.
回答2:
NSString *countryCode = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];
will get you an identifier like e.g. "US" (United States), "ES" (Spain), etc.
回答3:
use NSLocale
for fetch country Name
like
NSString *CodeofCountry = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
NSString *countryName = [[NSLocale currentLocale] displayNameForKey:NSLocaleCountryCode value:CodeofCountry];
NSLog(@" Code:%@ Name:%@",CodeofCountry, countryName);
//Code:IN Name:India
Source Link:
else use CLLocationManager
to get current location & CLGeocoder
to perform reverse-geocoding. You can get country name
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if (locations == nil)
return;
self.currentLocation = [locations objectAtIndex:0];
[self.geocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (placemarks == nil)
return;
self.currentLocPlacemark = [placemarks objectAtIndex:0];
NSLog(@"Current country: %@", [self.currentLocPlacemark country]);
NSLog(@"Current country code: %@", [self.currentLocPlacemark ISOcountryCode]);
}];
}
else use NSTimeZone
,
NSLog(@"country Name: %@", [NSTimeZone localTimeZone].name);
NSLog(@"abbrevationbs %@",[NSTimeZone localTimeZone].abbreviation);
来源:https://stackoverflow.com/questions/33784543/most-accurate-way-to-automatically-get-users-country-on-ios