我必須在iPhone設置中獲取當前國家/地區。任何人都可以告訴我如何在iPhone應用程序中獲取當前國家/地區。從iPhone設備中查找當前國家
我必須使用當前的國家來解析RSS feed,我需要通過當前的國家/地區。
請幫我找到國家。
在此先感謝。
我必須在iPhone設置中獲取當前國家/地區。任何人都可以告訴我如何在iPhone應用程序中獲取當前國家/地區。從iPhone設備中查找當前國家
我必須使用當前的國家來解析RSS feed,我需要通過當前的國家/地區。
請幫我找到國家。
在此先感謝。
要找到用戶選擇的語言的國家或地區:
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's answer。
如果您想查找設備物理位置的國家代碼,則需要CoreLocation進行反向地理編碼。看到這個問題詳細:How can I get current location from user in iOS
NSTimeZone *gmt = [NSTimeZone localTimeZone];
NSLog(@"timezone gmt %@",gmt.abbreviation);
NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *country = [locale displayNameForKey: NSLocaleCountryCode value: countryCode];
代碼片段工作正常,但突然開始在最後一行發出Exc_Bad_Access錯誤..! – tGilani 2012-07-03 10:36:58
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
它應該是NSLog(@「國家代碼:%@名稱:%@」,countryCode,國家); – AlexanderZ 2015-08-31 14:51:33
如果您正在測試並希望使用與系統不同的語言,則最簡單的方法是更改計劃的Application Language
和Application Region
選項,而不是更改設備或模擬器上的語言和區域。
轉到Product
- >Scheme
- >Edit Scheme...
- >Run
- >Options
並選擇Application Language
和Application Region
你想測試。
如果您認爲這是一個不好的答案,請發表評論關於爲什麼,我自己使用這個策略,並且據我所知它運行良好,但如果有問題,我很想知道它們! – 2016-02-04 17:06:36
雨燕3.0解決方案
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}
爲什麼不簡單地使用'Locale.current.regionCode'? – redent84 2017-03-28 12:40:22
對於SIM卡的設備,您可以使用此:
CTTelephonyNetworkInfo * network_Info = [CTTelephonyNetworkInfo new];
CTCarrier * carrier = network_Info.subscriberCellularProvider;
NSString * countryCode = [carrier.isoCountryCode uppercaseString];
Swift 3.0最新的工作代碼是
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}
這個國家是iPhone的本地化設置還是iPhone當前所在的國家? – JeremyP 2010-10-15 09:10:00