NSString with emoticons / emojis url encode

I'm trying to take the content of a UITextField, which can contain special characters and emojis, and turn it into something that I can pass in a GET request to a PHP service.

If I don't encode the string at all, the emojis show up just fine (I can see them in the DB and they come back to me) ... but if I add special characters (~! @ # $% Etc.) the GET request is throttled ...

So, I run the line through the url encoder:

[commentText stringByAddingPercentEscapesUsingEncoding:NSNonLossyASCIIStringEncoding];

      

I am using NSNonLossyASCIIStringEncoding to get emojis correctly, which works, but using this to encode it returns a null string. In fact, the only encoding that does not return null is UTF8, but this results in a unicode emoji with percentages.

How should I do it? Should I write my own string replacement for this case, or is there an iOS way I can't see?

Greetings,

Chris

+1


source to share


3 answers


NSNonLossyASCIIStringEncoding

to stringByAddingPercentEscapesUsingEncoding:

returns nil

because the string you are passing in is not ASCII. The use of NSUTF8StringEncoding

percent eludes emoji symbols and that's the result I expect. If your server side middleware does not automatically override emoji from the query string, then you should look for this in your server side code if it causes upstream problems.



+5


source


Use this to avoid emoji:

NSString *escapedEmoji = [NSString stringWithCString:[emojiString cStringUsingEncoding:NSNonLossyASCIIStringEncoding] encoding:NSUTF8StringEncoding];

      



And this is for the unescape emoji:

NSString *unescapedEmoji = [NSString stringWithCString:[escapedString cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];

      

+6


source


You can use below code to encode emoji string

NSString *uniText = [NSString stringWithUTF8String:[youremojistring UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];

      

+2


source







All Articles