项目中原来使用的方法:
- (BOOL)ContainsEmoji:(NSString *)inputString
{
__block BOOL isEomji = NO;
[inputString enumerateSubstringsInRange:NSMakeRange(0, [inputString 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) {
isEomji = YES;
}
}
} else if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3 || ls == 0xfe0f) {
isEomji = YES;
}
} else {
if (0x2100 <= hs && hs <= 0x27ff) {
isEomji = YES;
} else if (0x2B05 <= hs && hs <= 0x2b07) {
isEomji = YES;
} else if (0x2934 <= hs && hs <= 0x2935) {
isEomji = YES;
} else if (0x3297 <= hs && hs <= 0x3299) {
isEomji = YES;
} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
isEomji = YES;
}
}
}];
return isEomji;
}
发现有一些emoji会遗漏过去,如: 等;
调试发现,被识别出来的在 0x1d000 <= uc && uc <= 0x1F77F 这两个值之间,而 的值更大。于是找到 UNICODE EMOJI,知道最新版本的emoji是14.0,发布日期:2021-08-25。
然后在文档中找到14.0版本中emoji编码的最大值:0x1FAF6,于是将识别的范围改为:0x1d000 <= uc && uc <= 0x1FAF6,测试过后,上述遗漏的emoji都被拦截了。
麻烦的点是emoji更新后,需要手动更新代码,有不对、遗漏的地方或者大家有更好的方法,希望不吝赐教。
----------------------------------------------------------------这是一条分割线----------------------------------------------------------
发现一个大佬用正则表达式写的简洁方法:
NSString *inputString = @"abcd123 ";
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007e\\u00a0-\\u00be\\u2e80-\\ua4cf\\uf900-\\ufaff\\ufe30-\\ufe4f\\uff00-\\uffef\\u0080-\\u009f\\u2000-\\u201f\r\n]" options:0 error:nil];
NSString *result = [regularExpression stringByReplacingMatchesInString:inputString options:0 range:NSMakeRange(0, inputString.length) withTemplate:@""];
另外可以直接不让emoji输入,不过 currentInputMode 官方不建议使用了:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString:@"emoji"]) {
return false;
}
return true;
}