iOS-Emoji转换成NSString

Wechat的Emoji消息在iOS系统上显示。

Wechat里面对Emoji的消息处理为:

1
2
<span class=\"emoji emoji1f319\"></span>
<span class=\"emoji emoji2b50\"></span>

为了在iOS上显示,必须将其转换为字符串:

1
2
"\U0001f319"
"\U00002b50"

转换方式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
+ (NSString*)replaceEmojiChars:(NSString*)string
{
while(string != nil && string.length > 0){
NSString *base = @"\U0001F000";
NSString *prefix = @"<span class=\"emoji emoji", *postfix = @"\"></span>";
NSRange preRange = [string rangeOfString:prefix], postRange = [string rangeOfString:postfix];
if(preRange.length != 0 && postRange.length != 0){
unsigned int low = 0;
unichar chars[2];
[base getCharacters:chars];
NSString *replaceString = nil;
if(postRange.location - preRange.location - preRange.length > 4){
NSString *lowString = [string substringWithRange:NSMakeRange(postRange.location - 3, 3)];
[[NSScanner scannerWithString:[@"0x" stringByAppendingString:lowString]] scanHexInt:&low];
chars[0] += low / 1024;
chars[1] += low % 1024;
replaceString = [[NSString alloc] initWithCharacters:chars length:2];
}else{
NSString *lowString = [string substringWithRange:NSMakeRange(preRange.location + preRange.length, postRange.location - preRange.location - preRange.length)];
[[NSScanner scannerWithString:[@"0x" stringByAppendingString:lowString]] scanHexInt:&low];
chars[0] = low;
replaceString = [[NSString alloc] initWithCharacters:chars length:1];
}
string = [string stringByReplacingCharactersInRange:NSMakeRange(preRange.location, postRange.location - preRange.location + postRange.length) withString:replaceString];
}else{
break;
}
}
return string;
}

核心思想为:一个Emoji表情如果是5位的,例如”1F400”,则用两个unichar表示,如果是4位以下的,则用一个unichar表示。对于5位的,以@”\U0001F000”为基准,先转为十进制,上位加上1024的除数,下位加上1024的余数,对于4位的,直接加上数字即可。

YI wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!