问题起因:

原代码直接将库文件拖入项目使用的,现改为 pod 管理第三方库。PinYin4Objc 支持pod管理,所以直接删除原代码使用pod。

PinYin4Objc 库包含一个拼音文件,第一次使用该库会缓存到本地(这也是为什么修改后测试没发现异常)。

新装App(或删除再安装)转换汉字拼音失效,因为这个库直接从bundle中读取拼音资源文件路径,但是pod中的路径和项目中是不同的,导致没有读取到文件,本地缓存了一个错误数据文件。所以无法识别。

修改:

1、将资源文件复制一份放入项目中,这样还可以使用pod管理库文件;

2、写一个清除缓存的代码,在App启动时调用;

没有识别到拼音,删除缓存文件;

因为 PinYin4Objc 库实例化使用的单例,只会执行一次读取本地文件或缓存的机会,所以这里删除缓存后调用初始化资源文件的方法。

/// 清除拼音缓存文件
+ (void)removeCache
{
NSString *sourceText=@"我爱中文";
HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
[outputFormat setToneType:ToneTypeWithoutTone];
[outputFormat setVCharType:VCharTypeWithV];
[outputFormat setCaseType:CaseTypeLowercase];

// 汉字转为拼音
NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@""];
if ([outputPinyin isEqualToString:@"woaizhongwen"]) {
// 识别正确不做处理
return;
}

NSString *cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *_directory = [[[cachesDirectory stringByAppendingPathComponent:[[NSBundle mainBundle] bundleIdentifier]] stringByAppendingPathComponent:@"PinYinCache"] copy];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:_directory])
{
// 删除缓存
[fileManager removeItemAtPath:_directory error:nil];
}
// 初始化资源文件
[[ChineseToPinyinResource getInstance] initializeResource];
}

库链接:​​PinYin4Objc​

pod ‘PinYin4Objc’

然而我在demo中使用pod引入库照样可以识别拼音,这是为什么呢?

读取pod资源文件的方法

NSString *resourceName =[[NSBundle bundleForClass:[self class]] pathForResource:@"unicode_to_hanyu_pinyin" ofType:@"txt"];