Dharmbir Singh
Dharmbir Singh

Reputation: 17535

Unicode not working properly in iOS

My unicode is \u20AC when I set it on UILabel but I'm getting unicode on label. Some time it is printing euro but mostly it is printing unicode on label.

My code is over here

    NSLog(@"Currecy %@",currencySymbol);
    UILabel *priceLbl = [[UILabel alloc] initWithFrame:CGRectMake(180, 10, 45, 25)];

    priceLbl.textColor = [UIColor whiteColor];
    priceLbl.textAlignment = NSTextAlignmentCenter;
    priceLbl.font = [UIFont fontWithName:@"ProximaNova-Bold" size:15];
    priceLbl.tag  = 1001;
    fair = [NSString stringWithFormat:@"%d",arc4random()%50];
    priceLbl.text = [NSString stringWithFormat:@"%@ %@",fair,currencySymbol];

Output Currecy \u20AC

Printing description of priceLbl:
<UILabel: 0x7faade3095a0; frame = (185 10; 50 25); text = '\u20AC'; userInteractionEnabled = NO; tag = 1001; layer = <_UILabelLayer: 0x7faadbd91bb0>>

enter image description here

And I'm trying to set at my end getting output as I would like. for example

enter image description here

Getting server response

{
    currency = "\\u20AC";
    description = "You have been successfully logged in.";
}

and the currency symbol replacing "\\" with "\"

NSString *currency = [response[@"currency"] stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];

Upvotes: 1

Views: 1042

Answers (3)

hasan
hasan

Reputation: 24195

NGUYEN MINH answer worked for me as follow:

NSString *currencySymbol = @"\\u20AC";
NSString *fair = @"1.99 ";

NSString *convertedString = currencySymbol;

CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);

label.text = [NSString stringWithFormat:@"%@ %@", fair, convertedString];

The problem is that your currencySymbol contains: @"\\u20AC" which is a string of 6 characters not the one character string @"\u20AC"

Another working solution:

NSString *currencySymbol = @"\\u20AC";
NSString *fair = @"1.99 ";

currencySymbol = [NSString
                   stringWithCString:[currencySymbol cStringUsingEncoding:NSUTF8StringEncoding]
                   encoding:NSNonLossyASCIIStringEncoding];


label.text = [NSString stringWithFormat:@"%@ %@", fair, currencySymbol];

Upvotes: 3

gnasher729
gnasher729

Reputation: 52632

You are confusing the output of NSLog with the real data.

\u20ac is how NSLog displays a Euro symbol, because the Euro symbol is the Unicode character u20ac.

Upvotes: 0

NGUYEN MINH
NGUYEN MINH

Reputation: 26

please try:

NSString *convertedString = @"some text"; //Your unicode string here
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
yourLabel.text = convertedString;

Upvotes: 1

Related Questions