如果項(xiàng)目中有評(píng)論或者信息恢復(fù)的地方饥漫,往往會(huì)用到emoji,有時(shí)候如后臺(tái)不支持emoji,就會(huì)顯示亂碼錯(cuò)誤诊胞,我們可以把emoji轉(zhuǎn)成unicode編碼或者utf8編碼格式傳給服務(wù)器。當(dāng)然如果后臺(tái)服務(wù)器接收的時(shí)候能做好判斷識(shí)別最好锹杈,我們這邊后臺(tái)是支持的撵孤,我僅記錄一下方法,以備不時(shí)之需竭望。
先定義一個(gè)UITextView 并設(shè)置代理
設(shè)定一個(gè)宏定義邪码,用來判斷emoji
#defineMULITTHREEBYTEUTF16TOUNICODE(x,y) (((((x ^ 0xD800) << 2) | ((y ^ 0xDC00) >> 8)) << 8) | ((y ^ 0xDC00) & 0xFF)) + 0x10000
下面寫代理方法實(shí)現(xiàn)的內(nèi)容
- (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 去除前面六個(gè)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;
}
在輸入的時(shí)候,會(huì)自動(dòng)把輸入內(nèi)容轉(zhuǎn)成相應(yīng)的格式咬清。
如果在有些地方不需要輸入emoji表情闭专,可以做相關(guān)限制。
我這邊用到的是旧烧,如果用戶輸入emoji表情的時(shí)候影钉,會(huì)給出提示
//是否含有表情
- (BOOL)stringContainsEmoji:(NSString *)string
{
__block BOOL returnValue = NO;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:0];
if (0xd800 <= hs && hs <= 0xdbff) {
if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f77f) {
returnValue = YES;
}
}
} else if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
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;
}
通過調(diào)用該方法,如果返回的是YES則輸入內(nèi)容含有emoji掘剪,反之平委。