項目中原來使用的方法:
- (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;
}
發(fā)現(xiàn)有一些emoji會遺漏過去拴曲,如:?? ?? ?? ?? ?? ?? 等苔巨;
調(diào)試發(fā)現(xiàn),被識別出來的在 0x1d000 <= uc && uc <= 0x1F77F 這兩個值之間,而?? 的值更大遭贸。于是找到 UNICODE EMOJI,知道最新版本的emoji是14.0遣妥,發(fā)布日期:2021-08-25品姓。
然后在文檔中找到14.0版本中emoji編碼的最大值:0x1FAF6,于是將識別的范圍改為:0x1d000 <= uc && uc <= 0x1FAF6本缠,測試過后斥扛,上述遺漏的emoji都被攔截了。
麻煩的點是emoji更新后丹锹,需要手動更新代碼稀颁,有不對、遺漏的地方或者大家有更好的方法楣黍,希望不吝賜教匾灶。
----------------------------------------------------------------這是一條分割線----------------------------------------------------------
發(fā)現(xiàn)一個大佬用正則表達式寫的簡潔方法:
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;
}