意外发现微信获取的用户名 带有emoji 然后与后台交互就出问题了
emoji的问题就是字符编码超过了4位 导致后台数据库不支持 后台试了下来说出问题的地方太多不能改 就只好前端过滤emoji了
因为是四位编码出问题所以 就写了如下 把四位编码的字符改为""的方法
+ (NSString *)filterMoreThanFourString:(NSString *)string {
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *newStr = @"";
for(int i =0; i < [string length]; ){
NSString *temp = nil;
for (int j = 1; j <= string.length - i; j++) {
temp = [string substringWithRange:NSMakeRange(i,j)];
temp = [temp stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if (temp) {
i += j;
// NSLog(@"占%d位的字符:%@",j,temp);
break;
}
}
// NSLog(@"%d位最后的字是:%@",i,temp);
if ([temp lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 3) {
temp = @"";
}
newStr = [NSString stringWithFormat:@"%@%@",newStr,temp];
}
return newStr;
}
稍微改动成 多位字符替换的成指定字符的方法:
#pragma mark 过滤max位以上字符(不包括
+ (NSString *)filterMoreThanNumber:(NSInteger)maxNum String:(NSString *)string replaceString:(NSString *)replaceString UsingEncoding:(NSStringEncoding)usingEncoding{
string = [string stringByAddingPercentEscapesUsingEncoding:usingEncoding];
NSString *newStr = @"";
for(int i =0; i < [string length]; ){
NSString *temp = nil;
for (int j = 1; j <= string.length - i; j++) {
temp = [string substringWithRange:NSMakeRange(i,j)];
temp = [temp stringByReplacingPercentEscapesUsingEncoding:usingEncoding];
//只验证了NSUTF8StringEncoding 2017.04.01之前的编码格式下 上一句如果获取的字符不正常temp == nil
if (temp) {
i += j;
NSLog(@"占%d位的字符:%@",j,temp);
break;
}
}
NSLog(@"%d位最后的字是:%@",i,temp);
if ([temp lengthOfBytesUsingEncoding:usingEncoding] > maxNum) {
temp = replaceString;
}
newStr = [NSString stringWithFormat:@"%@%@",newStr,temp];
}
return newStr;
}
网友评论