2010-10-15 14 views
45

我必須在iPhone設置中獲取當前國家/地區。任何人都可以告訴我如何在iPhone應用程序中獲取當前國家/地區。從iPhone設備中查找當前國家

我必須使用當前的國家來解析RSS feed,我需要通過當前的國家/地區。

請幫我找到國家。

在此先感謝。

+3

這個國家是iPhone的本地化設置還是iPhone當前所在的國家? – JeremyP 2010-10-15 09:10:00

回答

124

要找到用戶選擇的語言的國家或地區:

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

+0

+1不錯,我學習新東西,請告訴我可以得到更多的信息.​​.. – Saawan 2010-10-15 08:44:27

+1

@ranjeet:你可以在http://developer.apple.com/library/ios/#documentation/找到NSLocale的參考資料。可可/參考/基礎/班/ NSLocale_Class /參考/的reference.html。 – kennytm 2010-10-15 08:46:32

+0

非常感謝。我得到了答案。 – AppAspect 2010-10-16 11:29:29

3
NSTimeZone *gmt = [NSTimeZone localTimeZone]; 

NSLog(@"timezone gmt %@",gmt.abbreviation); 
16
NSLocale *locale = [NSLocale currentLocale]; 
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode]; 
NSString *country = [locale displayNameForKey: NSLocaleCountryCode value: countryCode]; 
+0

代碼片段工作正常,但突然開始在最後一行發出Exc_Bad_Access錯誤..! – tGilani 2012-07-03 10:36:58

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 

Source Link

+0

它應該是NSLog(@「國家代碼:%@名稱:%@」,countryCode,國家); – AlexanderZ 2015-08-31 14:51:33

4

如果您正在測試並希望使用與系統不同的語言,則最簡單的方法是更改​​計劃的Application LanguageApplication Region選項,而不是更改設備或模擬器上的語言和區域。

轉到Product - >Scheme - >Edit Scheme... - >Run - >Options並選擇Application LanguageApplication Region你想測試。

Edit Application Language and Application Region within Scheme Run Options

從IOS文件:Testing Your Internationalized App

+0

如果您認爲這是一個不好的答案,請發表評論關於爲什麼,我自己使用這個策略,並且據我所知它運行良好,但如果有問題,我很想知道它們! – 2016-02-04 17:06:36

3

雨燕3.0解決方案

if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String { 
      print(countryCode) 
     } 
+4

爲什麼不簡單地使用'Locale.current.regionCode'? – redent84 2017-03-28 12:40:22

4

對於SIM卡的設備,您可以使用此:

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

Swift 3.0最新的工作代碼是

if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String { 
    print(countryCode) 
}