First I will try to provide a solution. Then I will try to explain why.
Escaping non-ASCII characters
To avoid unicode characters in a string, you should not rely on NSNonLossyASCIIStringEncoding . Below is the code that I use to remove unicode & non-ASCII characters in a string:
// NSMutableString category - (void)appendChar:(unichar)charToAppend { [self appendFormat:@"%C", charToAppend]; } // NSString category - (NSString *)UEscapedString { char const hexChar[] = "0123456789ABCDEF"; NSMutableString *outputString = [NSMutableString string]; for (NSInteger i = 0; i < self.length; i++) { unichar character = [self characterAtIndex:i]; if ((character >> 7) > 0) { [outputString appendString:@"\\u"]; [outputString appendChar:(hexChar[(character >> 12) & 0xF])]; // append the hex character for the left-most 4-bits [outputString appendChar:(hexChar[(character >> 8) & 0xF])]; // hex for the second group of 4-bits from the left [outputString appendChar:(hexChar[(character >> 4) & 0xF])]; // hex for the third group [outputString appendChar:(hexChar[character & 0xF])]; // hex for the last group, eg, the right most 4-bits } else { [outputString appendChar:character]; } } return [outputString copy]; }
( NOTE: I think the Jon Rose method does the same, but I do not want to use a method that I have not tested)
Now you have the following line: Copy right symbol : \u00A9 AND Registered Mark symbol : \u00AE
Unicode escaping is in progress. Now bring it back to display emojis.
Conversion back
This is confusing at first, but here is what it is:
NSData *data = [escapedString dataUsingEncoding:NSUTF8StringEncoding]; NSString *converted = [[NSString alloc] data encoding:NSNonLossyASCIIStringEncoding];
Now you have your emojis (and other non-ASCII).
What's happening?
Problem
In your case, you are trying to create a common language between the server and your application. However, NSNonLossyASCIIStringEncoding is a pretty poor choice for this purpose. Because this is a black box created by Apple, and we really don’t know what exactly it does inside. As we can see, it converts unicode to \uXXXX , converting non-ASCII characters to \XXX . That is why you should not rely on this to build a multi-platform system. There is no equivalent on backend platforms and Android.
However, it is rather cryptic that NSNonLossyASCIIStringEncoding can convert back to ® from \u00AE , while it converts it to \256 in the first place. I am sure that on other platforms there are tools to convert \uXXXX to unicode characters, this should not be a problem for you.
Mert buran
source share