如果项目中有评论或者信息恢复的地方,往往会用到emoji,有时候如后台不支持emoji,就会显示乱码错误,我们可以把emoji转成unicode编码或者utf8编码格式传给服务器。当然如果后台服务器接收的时候能做好判断识别最好,我们这边后台是支持的,我仅记录一下方法,以备不时之需。
先定义一个UITextView 并设置代理
设定一个宏定义,用来判断emoji
<pre>
define MULITTHREEBYTEUTF16TOUNICODE(x,y) (((((x ^ 0xD800) << 2) | ((y ^ 0xDC00) >> 8)) << 8) | ((y ^ 0xDC00) & 0xFF)) + 0x10000
</pre>
下面写代理方法实现的内容
<pre>
-
(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *hexstr = @"";for (int i=0;i< [text length];i++)
{
hexstr = [hexstr stringByAppendingFormat:@"%@",[NSString stringWithFormat:@"0x%1X ",[text characterAtIndex:i]]];
}
NSLog(@"UTF16 [%@]",hexstr);hexstr = @"";
long slen = strlen([text UTF8String]);
for (int i = 0; i < slen; i++)
{
//fffffff0 去除前面六个F & 0xFF
hexstr = [hexstr stringByAppendingFormat:@"%@",[NSString stringWithFormat:@"0x%X ",[text UTF8String][i] & 0xFF ]];
}
NSLog(@"UTF8 [%@]",hexstr);hexstr = @"";
if ([text length] >= 2) {
for (int i = 0; i < [text length] / 2 && ([text length] % 2 == 0) ; i++) { // three bytes if (([text characterAtIndex:i*2] & 0xFF00) == 0 ) { hexstr = [hexstr stringByAppendingFormat:@"Ox%1X 0x%1X",[text characterAtIndex:i*2],[text characterAtIndex:i*2+1]]; } else {// four bytes hexstr = [hexstr stringByAppendingFormat:@"U+%1X ",MULITTHREEBYTEUTF16TOUNICODE([text characterAtIndex:i*2],[text characterAtIndex:i*2+1])]; } } NSLog(@"(unicode) [%@]",hexstr);
}
else
{
NSLog(@"(unicode) U+%1X",[text characterAtIndex:0]);
}return YES;
}
</pre>
网友评论