Reputation: 209
I am trying this:
NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
It creates NSLocale object but it does`t contain any regional information. For example,
[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];
returns nil;
Any idea how to get NSLocale from currency code?
Upvotes: 7
Views: 4972
Reputation: 21510
You can use the power of extensions in Swift:
extension NSLocale {
static func currencySymbolFromCode(code: String) -> String? {
let localeIdentifier = NSLocale.localeIdentifierFromComponents([NSLocaleCurrencyCode : code])
let locale = NSLocale(localeIdentifier: localeIdentifier)
return locale.objectForKey(NSLocaleCurrencySymbol) as? String
}
}
In this way, anywhere in your code:
let code = "EUR"
let price = 10
if let currencySymbol = NSLocale.currencySymbolFromCode(code) as? String {
print("You have to pay \(price)\(currencySymbol)")
}
Upvotes: 1
Reputation: 16664
NSDictionary *localeInfo = @{NSLocaleCurrencyCode: currencyCode, NSLocaleLanguageCode: [[NSLocale preferredLanguages] objectAtIndex:0]};
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:
[NSLocale localeIdentifierFromComponents:localeInfo]];
Upvotes: 6
Reputation: 81
As posted by some Guest in pastebin:
NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];
Upvotes: 8
Reputation: 6103
There are tricks like creating locale with id but instead of normal locale id like "en_US" pass it currency code "USD", "EUR", etc., It seems to work for eur and usd in a way I could check it but this is wrong way IMHO.
The only right way I know is to get all locales and then in loop check their currency codes to compare with one you have. This way you will stop the loop when you find your code.
- (NSLocale *) findLocaleByCurrencyCode:(NSString *)_currencyCode
{
NSArray *locales = [NSLocale availableLocaleIdentifiers];
NSLocale *locale = nil;
NSString *localeId;
for (localeId in locales) {
locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeId] autorelease];
NSString *code = [locale objectForKey:NSLocaleCurrencyCode];
if ([code isEqualToString:_currencyCode])
break;
else
locale = nil;
}
/* For some codes that locale cannot be found, init it different way. */
if (locale == nil) {
NSDictionary *components = [NSDictionary dictionaryWithObject:_currencyCode
forKey:NSLocaleCurrencyCode];
localeId = [NSLocale localeIdentifierFromComponents:components];
locale = [[NSLocale alloc] initWithLocaleIdentifier:localeId];
}
return locale;
}
Upvotes: 5