最近在开发的过程中发现发送到服务的Emoji表情不能正确的编解码😂, 经过搜索发现Emoji的编码是UTF-16。为了保证服务器能够正确的存储必须把上传的带有Emoji的字符串编码成UTF-8,以下是我的实现:
//把字符串编码为UTF-8
- (NSString *)encodeEmojString:(NSString *)original
{
if (!original) {
return nil;
}
NSString *uniText = [NSString stringWithUTF8String:[original UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return goodMsg;
}
//把服务器返回的字符串转换为可以显示的字符串
- (NSString *)decodeEmojString:(NSString *)original
{
if (!original) {
return nil;
}
const char *jsonString = [original UTF8String];
NSData *dataNew = [NSData dataWithBytes: jsonString length:strlen(jsonString)];
NSString *msg = [[NSString alloc] initWithData:dataNew encoding:NSNonLossyASCIIStringEncoding];
return msg;
}
最后附上参考链接: