在接入环信SDK之后,得知服务器端加这个敏感词库是增值服务,并且价格还不菲,在百度谷歌之后,实现了从iOS 端处理这个问题。
下面我把代码贴出来。
.h文件
//// GJWordConfig.h// GameJourney//// Created by 文丹 on 2017/5/11.// Copyright © 2017年 Vinvinda. All rights reserved.//#import@interface GJWordConfig : NSObject
// 构造方法
+ (instancetype)sharedInstance;
//初始化词库
- (void)initData;
//转换
- (NSString *)filter:(NSString *)str;
//释放
- (void)freeFilter;
//
- (void)stopFilter:(BOOL)b;
@end
.m文件
//
// GJWordConfig.m
// GameJourney
//
// Created by 文丹 on 2017/5/11.
// Copyright © 2017年 Vinvinda. All rights reserved.
//
#import "GJWordConfig.h"
#define EXIST @"isExists"
@interface GJWordConfig()
@property (nonatomic,strong) NSMutableDictionary *root;
@property (nonatomic,assign) BOOL isFilterClose;
@end
static GJWordConfig *instance;
@implementation GJWordConfig
+ (instancetype)sharedInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc]init];
});
return instance;
}
- (void)initData{
self.root = [NSMutableDictionary dictionary];
//这一段是我们这里的网络请求,你们可以有自己的同步策略,当然实现的原理都是一样的。实现都一样的。我们是单例模式,每次启动都又创建一次。
[[DataManager manager]getAllWordsWithBlcok:^(id data, NSError *error) {
if (data && [data[@"status"] integerValue] == 1 && [data[@"data"] count] > 0 && [data[@"code"] integerValue] == 200){
//遍历服务器返回的string,然后插入
for (NSString *word in data[@"data"]) {
[self insertWords:word];
}
}else{
[[DataManager manager]showErrorInfo:data[@"message"]];
}
}];
}
-(void)insertWords:(NSString *)words{
NSMutableDictionary *dic = self.root;
for (int i = 0; i < words.length; i ++) {
NSString *word = [words substringWithRange:NSMakeRange(i, 1)];
if (dic[word] == nil) {
dic[word] = [NSMutableDictionary dictionary];
}
dic = dic[word];
}
//敏感词最后一个字符标识
dic[EXIST] = [NSNumber numberWithInt:1];
}
- (NSString *)filter:(NSString *)str{
//设置没有过期或者这个关键词是否存在
if (self.isFilterClose || !self.root) {
return str;
}
NSMutableString *result = result = [str mutableCopy];
for (int i = 0; i < str.length; i ++) {
NSString *subString = [str substringFromIndex:i];
NSMutableDictionary *node = [self.root mutableCopy] ;
int num = 0;
for (int j = 0; j < subString.length; j ++) {
NSString *word = [subString substringWithRange:NSMakeRange(j, 1)];
if (node[word] == nil) {
break;
}else{
num ++;
node = node[word];
}
//敏感词匹配成功
if ([node[EXIST]integerValue] == 1) {
NSMutableString *symbolStr = [NSMutableString string];
for (int k = 0; k < num; k ++) {
[symbolStr appendString:@"*"];
}
[result replaceCharactersInRange:NSMakeRange(i, num) withString:symbolStr];
i += j;
break;
}
}
}
return result;
}
- (void)freeFilter{
self.root = nil;
}
- (void)stopFilter:(BOOL)b{
self.isFilterClose = b;
}
@end
希望以上能够帮到你。
2017.5.15
Vinvinda。