Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Locale.current.regionCode is nil?

Tags:

ios

ios9

swift

I am trying to get user's region code in swift 3 by using:

Locale.current.regionCode

Unfortunately regionCode is nil, do you have an idea why? And what should I do to obtain it?

Thanks a lot.

like image 535
thierryb Avatar asked Mar 06 '17 21:03

thierryb


3 Answers

For those looking for solutions at SIMULATOR, go to "Settings > General > Language & Region" and change the region.

It worked for me and other people.
For a weird unknown reason, some simulators doesn't return the region until it changes at least once.

I don't know if it works at real device as well, because I did not had this problem on real device.

like image 95
Eduardo Herzer Avatar answered Oct 20 '22 15:10

Eduardo Herzer


I ran into the same issue and as it turns out it was because I set my Scheme to a specific language. If you set both, Application Language & Application Region to "System Language / Region" it should work.

enter image description here

like image 9
Hannes Avatar answered Oct 20 '22 15:10

Hannes


Many of the properties on Locale can return nil for various reasons on iOS (and Android).

You may also use objectForKey:NSLocaleCountryCode to query the country code.

// code may be nil
NSString *code = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]; 

It's a good idea to have a fallback logic to find countryCode with CoreTelephony.

CTCarrier *carrier = [[CTTelephonyNetworkInfo new] subscriberCellularProvider];
NSString *countryCode = carrier.isoCountryCode;

Or/And with reverse geocode:

// CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    __block CLLocation *location = [locations firstObject];

    [[[CLGeocoder alloc] init] reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error && placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks firstObject];
            // Use placemark.country;
            // Use placemark.ISOCountryCode;
        }
    }
}

For instance, on Android version of corresponding region query for Locale, it's nil for many of the rooted devices.

like image 2
lal Avatar answered Oct 20 '22 15:10

lal