我必须在 iPhone 设置中获取当前国家/地区。谁能告诉我如何在 iPhone 应用程序中获取当前国家/地区。
我必须使用当前国家/地区来解析我需要传递当前国家/地区的 RSS 提要。
请帮我找出国家。
提前致谢。
我必须在 iPhone 设置中获取当前国家/地区。谁能告诉我如何在 iPhone 应用程序中获取当前国家/地区。
我必须使用当前国家/地区来解析我需要传递当前国家/地区的 RSS 提要。
请帮我找出国家。
提前致谢。
要查找用户所选语言的国家/地区:
NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale.
NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
// get country code, e.g. ES (Spain), FR (France), etc.
在斯威夫特:
let currentLocale = NSLocale.currentLocale()
let countryCode = currentLocale.objectForKey(NSLocaleCountryCode) as? String
如果您想查找当前时区的国家代码,请参阅@chings228 的答案。
如果您想查找设备物理位置的国家代码,则需要使用反向地理编码的 CoreLocation。有关详细信息,请参阅此问题:How can I get current location from user in iOS
NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *country = [locale displayNameForKey: NSLocaleCountryCode value: countryCode];
对于带有 SIM 卡的设备,您可以使用:
CTTelephonyNetworkInfo * network_Info = [CTTelephonyNetworkInfo new];
CTCarrier * carrier = network_Info.subscriberCellularProvider;
NSString * countryCode = [carrier.isoCountryCode uppercaseString];
对于 Swift 4.0,
你可以简单地使用
let countryCode = Locale.current.regionCode
print(countryCode)
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
源链接。
如果您正在测试并希望使用与您的系统不同的语言,最简单的方法是更改您的方案Application Language
和Application Region
选项,而不是更改设备或模拟器上的语言和区域。
转到Product
-> Scheme
-> Edit Scheme...
-> Run
->Options
并选择要测试的Application Language
和。Application Region
来自 iOS 文档:测试您的国际化应用程序
NSTimeZone *gmt = [NSTimeZone localTimeZone];
NSLog(@"timezone gmt %@",gmt.abbreviation);
Swift 3.0 最新的工作代码是
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}
Swift 3.0解决方案
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}