通常情况下在后台服务器没有进行专门处理的情况下会返回异常,这时在前端就需要进行相应的处理。
1.限制输入表情
通过一个专门的函数判断输入的文字中是否包含表情
在NSString+Extension的扩展类中加入该类方法
+ (BOOL)isContainsTwoEmoji:(NSString *)string
{
__block BOOL isEomji = NO;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:0];
// NSLog(@"hs++++++++%04x",hs);
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;
}
// NSLog(@"uc++++++++%04x",uc);
}
} else if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3|| ls ==0xfe0f) {
isEomji = YES;
}
// NSLog(@"ls++++++++%04x",ls);
} else {
if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
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;
}
2.对输入的文字内容进行相应的编码,在接收到后台返回的数据时进行相对应的解码
编码
A:
//
// NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)textView.text, (CFStringRef)@"!$&‘()*+,-./:;[email protected]_~%#[]", NULL, kCFStringEncodingUTF8));
B:
// NSString *uniStr = [NSString stringWithUTF8String:[textView.text UTF8String]];
// NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
// NSString *goodStr = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
解码:
A:
NSString *showText = [serverString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
B:
// const char *jsonString = [model.message UTF8String]; // goodStr 服务器返回的 json
// NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
// NSString *goodMsg1 = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
原文地址:https://www.cnblogs.com/fantasy940155655/p/8315480.html