从iPhone设备查找当前国家/地区

App*_*ect 50 iphone objective-c appsettings application-settings ios

我必须在iPhone设置中获取当前国家/地区.谁能告诉我如何在iPhone应用程序中获取当前国家/地区.

我必须使用当前国家来解析我需要通过当前国家/地区的RSS源.

请帮我找到这个国家.

提前致谢.

ken*_*ytm 137

要查找用户所选语言的国家/地区:

NSLocale *currentLocale = [NSLocale currentLocale];  // get the current locale.
NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
// get country code, e.g. ES (Spain), FR (France), etc.
Run Code Online (Sandbox Code Playgroud)

在Swift中:

let currentLocale = NSLocale.currentLocale()
let countryCode = currentLocale.objectForKey(NSLocaleCountryCode) as? String
Run Code Online (Sandbox Code Playgroud)

如果要查找当前时区的国家/地区代码,请参阅@ chings228的答案.

如果要查找设备物理位置的国家/地区代码,则需要使用反向地理编码的CoreLocation.有关详细信息,请参阅此问题:如何从iOS中获取用户的当前位置

  • 注意!如果使用手机的人实际上已将手机设置为使用其所在国家/地区的区域设置,则此功能非常有用.这不一定是这种情况,如果一个人可能正在休假并且您仍然需要检测他们所在的确切国家,则尤其没用. (21认同)
  • 我使用xcode 6和iOS模拟器(iPhone 6/iOS 8.1).无论我将iOS模拟器设置为什么语言和区域,我总是将美国作为countryCode.此外,[[NSLocale preferredLanguage] objectAtIndex:0]的输出始终为en.我怎么知道代码工作正常? (4认同)

小智 17

NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *country = [locale displayNameForKey: NSLocaleCountryCode value: countryCode];
Run Code Online (Sandbox Code Playgroud)


Tej*_*ina 9

NSLocale *countryLocale = [NSLocale currentLocale];  
NSString *countryCode = [countryLocale objectForKey:NSLocaleCountryCode];
NSString *country = [countryLocale displayNameForKey:NSLocaleCountryCode value:countryCode];
NSLog(@"Country Code:%@ Name:%@", countryCode, country);
//Country Code:IN Name:India
Run Code Online (Sandbox Code Playgroud)

来源链接.


小智 9

对于使用SIM卡的设备,您可以使用:

  CTTelephonyNetworkInfo * network_Info = [CTTelephonyNetworkInfo new];
  CTCarrier * carrier = network_Info.subscriberCellularProvider;
  NSString  * countryCode = [carrier.isoCountryCode uppercaseString];
Run Code Online (Sandbox Code Playgroud)


Meh*_*kar 9

对于Swift 4.0,

您可以简单地使用

let countryCode = Locale.current.regionCode

print(countryCode)


chi*_*228 5

NSTimeZone *gmt = [NSTimeZone localTimeZone];

NSLog(@"timezone gmt %@",gmt.abbreviation);
Run Code Online (Sandbox Code Playgroud)


Hea*_*ers 5

如果您正在测试并希望使用与系统不同的语言,则最简单的方法是更改​​您的方案Application LanguageApplication Region选项,而不是更改设备或模拟器上的语言和区域.

转到Product- > Scheme- > Edit Scheme...- > Run- > Options并选择Application LanguageApplication Region你想测试.

在Scheme Run Options中编辑应用程序语言和应用程序区域

从iOS文档:测试您的国际化应用程序