iOS 检测并过滤Emoji表情符号

将苹果键盘的Emoji表情符号过滤掉。
通过研究和测试,得到以下比较完美的解决方案,思路两条:

1.当用户切换键盘为Emoji表情时,输入的表情不响应(即表情符号不显示到UITextView或UITextField)。这里可以通过UITextView或UITextField的回调和是否为emoji键盘:

[[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"];

2.当用户通过中文键盘输入中文“哈哈”后出现可选文字中选中的Emoji笑脸,最后统一通过检查最终字符串textField.text的内容,通过Emoji筛unicode编码来判断是否存在Emoji表情,如果存在则提醒用户做修改。

主要的代码如下:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //如果允许继续输入,那么返回YES,否则返回NO
    //如果输入超过规定的字数140,就不再让输入
    // 不让输入表情
    if ([textView isFirstResponder]) {
        if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] ||
            ![[textView textInputMode] primaryLanguage] ||
            range.location >= MARK_WORD_LIMIT) {
            return NO;
        }
    }

    if ([textView isFirstResponder]) {
        if ([self stringContainsEmoji:text]) {
            return NO;
        }
    }
    //NSLog(@"%@",text);
    return YES;
}

/*由于联想输入的时候,函数textView:shouldChangeTextInRange:replacementText:无法判断字数,
 因此使用textViewDidChange对TextView里面的字数进行判断
 */
- (void)textViewDidChange:(UITextView *)textView
{
    //该判断用于联想输入
    if (textView.text.length > MARK_WORD_LIMIT)
    {
        textView.text = [textView.text substringToIndex:MARK_WORD_LIMIT];
    }
}

// 过滤所有表情
- (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;
}

你可能感兴趣的:(iOS 检测并过滤Emoji表情符号)