2012-10-01 18 views
19

Im recupero di un nome di paese da un server in inglese. Ad esempio, "Spain"Ottieni il codice del paese dal nome del paese in IOS

Quello che voglio fare è, supponendo che il nome del paese verrà scritto in inglese, ottenere il codice del paese.

Cosa devo fare? Ho trovato facile ottenere il nome del paese dal codice del paese, ma non ho idea di come fare l'operazione opposta.

Grazie mille.

+0

Come va il codice dal nome del paese? Basta fare il contrario :) – deanWombourne

+0

Spero che questo vi aiuterà a linke http://stackoverflow.com/questions/502764/iphone-obtaining-a-list-of-countries-in-an-nsarray –

+0

Ive già controllato, ma quello che voglio è quello di ottenere un solo CountryCode secondo un nome di paese, non un elenco di paesi – pdrcabrod

risposta

29

Jef's answer aiutato qui, con lievi aggiunte.

NSArray *countryCodes = [NSLocale ISOCountryCodes]; 
NSMutableArray *countries = [NSMutableArray arrayWithCapacity:[countryCodes count]]; 

for (NSString *countryCode in countryCodes) 
{ 
    NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]]; 
    NSString *country = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_UK"] displayNameForKey: NSLocaleIdentifier value: identifier]; 
    [countries addObject: country]; 
} 

NSDictionary *codeForCountryDictionary = [[NSDictionary alloc] initWithObjects:countryCodes forKeys:countries]; 

Passare attraverso la 'codeForCountryDictionary' con il nome del paese per il quale si richiede il codice, ad esempio,

NSLog(@"%@",[codeForCountryDictionary objectForKey:@"Spain"]); 

sarebbe cedere il risultato come 'ES', che è il 2 codice paese lettera per la Spagna.

+4

Beh, se si conosce il paese i nomi sono in inglese, si dovrebbe ovviamente non si utilizza il currentLocale, ma un locale fisso. Il currentLocale può essere in qualsiasi lingua. Utilizzare invece [NSLocale initWithLocaleIdentifier: @ "en_UK"]. – fishinear

+0

initWithLocaleIdentifier è un metodo di istanza, non è un metodo di classe, in modo da utilizzare '[[NSLocale alloc] initWithLocaleIdentifier: @ "it_IT"]' invece – pyrou

+0

Giusto per essere sicuro che avrei caso anche inferiore/superiore le chiavi del dizionario. Non siamo sicuri di cosa il server restituisce (che è un problema diverso, ma almeno in grado di ridurre al minimo la debolezza 'displayName') – surui

3

Nella Swift si intende utilizzare questo codice

extension NSLocale { 
    class func locales1(countryName1 : String) -> String { 
     var locales : String = "" 
     for localeCode in NSLocale.ISOCountryCodes() { 
      let countryName = NSLocale.systemLocale().displayNameForKey(NSLocaleCountryCode, value: localeCode)! 
      if countryName1.lowercaseString == countryName.lowercaseString { 
       return localeCode as! String 
      } 
     } 
     return locales 
    } 


} 

ottenere i dati:

strP2countrycode = NSLocale.locales1("PASS_COUNTRYNAME") 
1

La mia versione compatta compresa la correzione per la corrispondenza solo contro la versione inglese i nomi dei paesi.

extension NSLocale 
{ 
    class func localeForCountry(countryName : String) -> String? 
    { 
     return NSLocale.ISOCountryCodes().first{self.countryNameFromLocaleCode($0 as! String) == countryName} as? String 
    } 

    private class func countryNameFromLocaleCode(localeCode : String) -> String 
    { 
     return NSLocale(localeIdentifier: "en_UK").displayNameForKey(NSLocaleCountryCode, value: localeCode) ?? "" 
    } 
} 
0

qui è il codice Daxesh Negar a Swift 3

extension NSLocale { 
    class func locales1(countryName1 : String) -> String { 
     let locales : String = "" 
     for localeCode in NSLocale.isoCountryCodes { 
      let countryName = Locale.current.regionCode 
      if countryName1.lowercased() == countryName?.lowercased() { 
       return localeCode 
      } 
     } 
     return locales 
    } 
} 
1

Utilizzando rapida 3 (alcune delle risposte dovesse risultare mancante di un pezzo)

extension NSLocale { 
class func locales1(countryName1 : String) -> String { 
    let locales : String = "" 
    for localeCode in NSLocale.isoCountryCodes { 
     let countryName = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: localeCode) 
     if countryName1.lowercased() == countryName?.lowercased() { 
      return localeCode 
     } 
    } 
    return locales 
} 
} 
1

Swift 3.0:

Come codice del paese e nome del paese come NS Dictionary-

let countryCodes: [AnyObject] = NSLocale.isoCountryCodes as [AnyObject] 

     let countries: NSMutableArray = NSMutableArray(capacity: countryCodes.count) 

     for countryCode in countryCodes { 
      let identifier: String = NSLocale.localeIdentifier(fromComponents: NSDictionary(object: countryCode, forKey: NSLocale.Key.countryCode as NSCopying) as! [String : String]) 
      let country: String = NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: identifier)! 
      countries.add(country) 
     } 
     let codeForCountryDictionary: [NSObject : AnyObject] = NSDictionary(objects: countryCodes, forKeys: countries as! [NSCopying]) as [NSObject : AnyObject] 

     print(codeForCountryDictionary) 
2

a Swift 3 si può semplicemente utilizzare solo

let currentLocale = NSLocale.current 
var countries = NSLocale.isoCountryCodes 
currentLocale.localizedString(forRegionCode: countries.first!) 
+1

Codice-solo risposte sono scoraggiati perché non spiegano come si risolvono il problema. Si prega di aggiornare la risposta per spiegare come questo migliora le altre risposte accettate e potenziate che questa domanda ha già. Inoltre, questa domanda ha 5 anni, i tuoi sforzi sarebbero più apprezzati dagli utenti che hanno domande senza risposta recenti. Si prega di rivedere [Come scrivere una buona risposta] (https://stackoverflow.com/help/how-to-answer). – FluffyKitten

+1

Come puoi vedere la mia risposta è solo in 3 righe ed è migliore di altre IMO. Questa domanda è prima su google, quindi ho deciso di condividere la mia risposta. So che questa domanda ha 5 anni, ma molti sviluppatori hanno un problema. Se non sei d'accordo con me, cancella questo. –

0

Questo è come farlo a Swift 4.0 (lavorare anche a Swift 3.2).

NSLocale.isoCountryCodes.forEach { (code) in 
    print(code) 
    let name = NSLocale(localeIdentifier: "zh_CN").displayName(forKey: NSLocale.Key.countryCode, value: code) 
    print(name) 
} 
2

Un Swift 4 versione aggiornata del @Daxesh Nagar soluzione:

private func locale(for fullCountryName : String) -> String { 
    var locales : String = "" 
    for localeCode in NSLocale.isoCountryCodes { 
     let identifier = NSLocale(localeIdentifier: localeCode) 
     let countryName = identifier.displayName(forKey: NSLocale.Key.countryCode, value: localeCode) 
     if fullCountryName.lowercased() == countryName?.lowercased() { 
      return localeCode as! String 
     } 
    } 
    return locales 
} 

per questo ingresso come fullCountryName

"Regno Unito"

.210

verrà restituito il codice paese come segue

"GB"

Speranza che aiuta voi ragazzi!

0

Quindi questa soluzione funziona bene in rapida 4 prese da osservazioni di cui sopra ...

extension NSLocale { 
    struct Locale { 
    let countryCode: String 
    let countryName: String 
    } 

    class func locales() -> [Locale] { 

    var locales = [Locale]() 

    for localeCode in NSLocale.isoCountryCodes { 
     let identifier = NSLocale(localeIdentifier: localeCode) 
     let countryName = identifier.displayName(forKey: NSLocale.Key.countryCode, value: localeCode)! 
     let countryCode = localeCode 
     let locale = Locale(countryCode: countryCode, countryName: countryName) 
     locales.append(locale) 
    } 

    return locales.sorted{$0.countryName.localizedCaseInsensitiveCompare($1.countryName) == ComparisonResult.orderedAscending} 
} 
} 

godere!

Problemi correlati