NSString with emoticons/emojis url encode

你说的曾经没有我的故事 提交于 2019-11-29 23:53:04

问题


I am trying to take the contents of a UITextField that may contain special characters and emojis and turn it into something I can pass in a GET request to a PHP service.

If I do not encode the string at all, the emojis show up just fine (I can see them in the DB and they come back to me properly)... but if I add special chars (~!@#$%, etc.) the GET request chokes.

So I run the string through the url encoder:

[commentText stringByAddingPercentEscapesUsingEncoding:NSNonLossyASCIIStringEncoding];

I am using the NSNonLossyASCIIStringEncoding to get the emojis out properly, which works, but using this to encode returns a nil string. In fact, the only encoding that does not return a nil is UTF8, but that munges up the emoji unicode with percent-escapes.

How do I do this? Do I have to write my own string replacement for this case, or is there an iOS way to do it that I am not seeing?

Cheers,

Chris


回答1:


NSNonLossyASCIIStringEncoding to stringByAddingPercentEscapesUsingEncoding: returns nil because the string you're passing in is not ASCII. Using NSUTF8StringEncoding percent escapes the emoji characters and that's the result I would expect. If your server-side middleware is not automatically unescaping the emoji from the query string, then you should look to do that in your server-side code if it's causing issues upstream.




回答2:


Use this to escape emoji:

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

And this to unescape emoji:

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



回答3:


You can use the 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];


来源:https://stackoverflow.com/questions/19304535/nsstring-with-emoticons-emojis-url-encode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!