Most accurate way to automatically get user's country on iOS?

假如想象 提交于 2020-01-06 19:33:29

问题


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:

  1. Use a service like http://ipinfo.io/json or http://freegeoip.net/json/ to get the country code.
  2. Use the device's carrier code, I'll be able to get the country where they registered their mobile phone.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!