iOS emoji表情转码 或者判断

2022-11-19,,,

如果项目中有评论或者信息恢复的地方,往往会用到emoji,有时候如后台不支持emoji,就会显示乱码错误,我们可以把emoji转成unicode编码或者utf8编码格式传给服务器。当然如果后台服务器接收的时候能做好判断识别最好,我们这边后台是支持的,我仅记录一下方法,以备不时之需。

先定义一个UITextView 并设置代理

设定一个宏定义,用来判断emoji

 #define MULITTHREEBYTEUTF16TOUNICODE(x,y) (((((x ^ 0xD800) << 2) | ((y ^ 0xDC00) >> 8)) << 8) | ((y ^ 0xDC00) & 0xFF)) + 0x10000

下面写代理方法实现的内容

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *hexstr = @""; for (int i=;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 = ; i < slen; i++)
{
//fffffff0 去除前面六个F & 0xFF
hexstr = [hexstr stringByAppendingFormat:@"%@",[NSString stringWithFormat:@"0x%X ",[text UTF8String][i] & 0xFF ]];
}
NSLog(@"UTF8 [%@]",hexstr); hexstr = @""; if ([text length] >= ) { for (int i = ; i < [text length] / && ([text length] % == ) ; i++)
{
// three bytes
if (([text characterAtIndex:i*] & 0xFF00) == ) {
hexstr = [hexstr stringByAppendingFormat:@"Ox%1X 0x%1X",[text characterAtIndex:i*],[text characterAtIndex:i*+]];
}
else
{// four bytes
hexstr = [hexstr stringByAppendingFormat:@"U+%1X ",MULITTHREEBYTEUTF16TOUNICODE([text characterAtIndex:i*],[text characterAtIndex:i*+])];
} }
NSLog(@"(unicode) [%@]",hexstr);
}
else
{
NSLog(@"(unicode) U+%1X",[text characterAtIndex:]);
} return YES;
}

在输入的时候,会自动把输入内容转成相应的格式。

如果在有些地方不需要输入emoji表情,可以做相关限制。

我这边用到的是,如果用户输入emoji表情的时候,会给出提示

 //是否含有表情
- (BOOL)stringContainsEmoji:(NSString *)string
{
__block BOOL returnValue = NO; [string enumerateSubstringsInRange:NSMakeRange(, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:];
if (0xd800 <= hs && hs <= 0xdbff) {
if (substring.length > ) {
const unichar ls = [substring characterAtIndex:];
const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f77f) {
returnValue = YES;
}
}
} else if (substring.length > ) {
const unichar ls = [substring characterAtIndex:];
if (ls == 0x20e3) {
returnValue = YES;
}
} else {
if (0x2100 <= hs && hs <= 0x27ff) {
returnValue = YES;
} else if (0x2B05 <= hs && hs <= 0x2b07) {
returnValue = YES;
} else if (0x2934 <= hs && hs <= 0x2935) {
returnValue = YES;
} else if (0x3297 <= hs && hs <= 0x3299) {
returnValue = YES;
} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
returnValue = YES;
}
}
}]; return returnValue;
}

通过调用该方法,如果返回的是YES则输入内容含有emoji,反之。

iOS emoji表情转码 或者判断的相关教程结束。

《iOS emoji表情转码 或者判断.doc》

下载本文的Word格式文档,以方便收藏与打印。