iOS 获取emoji表情和拦截emoji表情
1
2
|
//将数字转为 #define EMOJI_CODE_TO_SYMBOL(x) (((( 0x808080F0 | (x & 0x3F000 ) >> 4 ) | (x & 0xFC0 ) << 10 ) | (x & 0x1C0000 ) << 18 ) | (x & 0x3F ) << 24 ); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
- ( void )viewDidLoad { [ super viewDidLoad]; //单独调用 int sym = EMOJI_CODE_TO_SYMBOL( 0x1F600 ); NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding]; NSLog( @arr ==%@,emoT); //获取数组 NSArray *arrEmotion = [self defaultEmoticons]; for (NSString *str in arrEmotion) { NSLog(@===%@,str); } } |
1
2
3
4
5
6
7
8
9
10
11
12
|
//获取默认表情数组 - (NSArray *)defaultEmoticons { NSMutableArray *array = [NSMutableArray new ]; for ( int i= 0x1F600 ; i<= 0x1F64F ; i++) { if (i < 0x1F641 || i > 0x1F644 ) { int sym = EMOJI_CODE_TO_SYMBOL(i); NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding]; [array addObject:emoT]; } } return array; } |
为了防止输入表情符号,需要对输入的内容做检测和过滤,将苹果键盘的Emoji表情符号过滤掉。
通过研究和测试,得到以下比较完美的解决方案,思路两条:
1,当用户切换键盘为Emoji表情时,输入的表情不响应(即表情符号不显示到UITextView或UITextField)。这里可以通过UITextView或UITextField的回调和是否为emoji键盘:
1 [[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"]
来判断;
2,当用户通过中文键盘输入中文“哈哈”后出现可选文字中选中的Emoji笑脸,最后统一通过检查最终字符串textField.text的内容,通过Emoji筛unicode编码来判断是否存在Emoji表情,如果存在则提醒用户做修改。
主要的代码如下:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// 不让输入表情
if ([textView isFirstResponder]) {
if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
return NO;
}
}
return YES;
}
// 过滤所有表情 https://gist.github.com/cihancimen/4146056
- (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];
// surrogate pair
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 {
// non surrogate
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;
}