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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With