最近项目需要iOS和安卓的emoji表情进行通用,这就需要转码,转成传说中的万能码,unicode码,但是网上的坑确实太多了,踩都踩不完,最后变体鳞伤的我,终于找到一个靠谱的方法,在这里于大家分享一下。
//unicode转NSString
+ (NSString*) replaceUnicode:(NSString*)aUnicodeString {NSString *tempStr1 = [aUnicodeString stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
mutabilityOption:NSPropertyListImmutable
format:NULL
errorDescription:NULL];
return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}
//NSString转Unicode
{
NSData* data = [str dataUsingEncoding:NSUnicodeStringEncoding];
char* unicodeChar = (char*)[data bytes];
//1.跳过unicode前面的FF-FE两个字节。
unicodeChar +=2;
[ToolUtil convertToBigEndian:unicodeChar Length:data.length-2];
NSString *stt = [@"" stringByAppendingString:[ToolUtil HttpUrlEncode:unicodeChar Length:data.length-2]];
return [ToolUtil modifyByUnicode:stt];
}
+ (NSString *)modifyByUnicode:(NSString *)unicodeStr {
NSArray *StrArr = [unicodeStr componentsSeparatedByString:@"\\u"];
NSString *str = @"";
NSString *lastStr = @"";
NSString *str1 = @"";
NSString *str2 = @"";
for (NSInteger i = 0; i < StrArr.count-1; i++) {
if (i%2 != 0) {
continue;
} else {
str1 = StrArr[i];
str2 = StrArr[i+1];
str = [NSString stringWithFormat:@"\\u%@%@",str1,str2];
lastStr = [lastStr stringByAppendingString:str];
}
}
return lastStr;
}
+ (NSString*) HttpUrlEncode:(char*)srcUrl Length:(NSInteger)len
{
if (len == 0)
{
return @"";
}
NSString* buf = @"";
// Parse a the chars in the url
for (int i=0; i<len; i++)
{
char oneChar = srcUrl[i];
buf = [buf stringByAppendingString:[ToolUtil UrlEncodeFormat:oneChar]];
if(i!= len-1)
{
buf = [buf stringByAppendingString:@"\\u"];
}
}
return buf;
}
+ (NSString*) UrlEncodeFormat:(u_char) cValue
{
NSString* buf=@"";
uint nDiv = cValue/16;
uint nMod = cValue%16;
buf = [buf stringByAppendingString:[ToolUtil DecimalToHexString:nDiv]];
buf = [buf stringByAppendingString:[ToolUtil DecimalToHexString:nMod]];
return buf;
}
+ (NSString*) DecimalToHexString:(u_char) nValue
{
NSString* tmp = @"";
switch(nValue)
{
case 0:tmp = @"0";break;
case 1:tmp = @"1";break;
case 2:tmp = @"2";break;
case 3:tmp = @"3";break;
case 4:tmp = @"4";break;
case 5:tmp = @"5";break;
case 6:tmp = @"6";break;
case 7:tmp = @"7";break;
case 8:tmp = @"8";break;
case 9:tmp = @"9";break;
case 10:tmp = @"A";break;
case 11:tmp = @"B";break;
case 12:tmp = @"C";break;
case 13:tmp = @"D";break;
case 14:tmp = @"E";break;
case 15:tmp = @"F";break;
default:tmp = @"X";
break;
}
return tmp;
}
+ (void) convertToBigEndian:(char*)src Length:(NSInteger)len
{
if(len%2 !=0)
{
return ;
}
char tmp;
for (int i=0; i<len; i+=2)
{
tmp = src [i];
src[i] = src[i+1];
src[i+1] = tmp;
}
}