写了个分类使用方法交换
iOS里面字符串转URL的时候里面有中文就会失败为nil,全部转换可能会出问题,有#这种转换后打不开。想统一处理,使用Category重写系统方法,原来使用URLWithString的会直接使用新的方法转换成功就继续,转换失败就转义中文后再试。
上代码.m文件如下:
#import "NSURL+XXX.h"
@implementation NSURL (XXX)
+(void)load
{
Method methodOld = class_getClassMethod([self class], @selector(URLWithString:));
Method methodNew = class_getClassMethod([self class], @selector(URLWithCHString:));
method_exchangeImplementations(methodOld, methodNew);
}
+(NSURL *)URLWithCHString:(NSString *)URLString
{
NSURL *url = [NSURL URLWithCHString:URLString];
if (url) {
return url;
}else{
NSString *str = [NSURL urlEncodeChineseString:URLString];
NSURL *urlCH = [NSURL URLWithCHString:str];
return urlCH;
}
}
//字符串转换只转码中文,不统一转换#等特殊字符会出问题
+ (NSString *)urlEncodeChineseString:(NSString *)string
{
//(unicode中文编码范围是0x4e00~0x9fa5)
for (int i = 0; i < string.length; i++) {
int utfCode = 0;
void *buffer = &utfCode;
NSRange range = NSMakeRange(i, 1);
BOOL b = [string getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)) {
NSString*bStr = [string substringWithRange:NSMakeRange(i,1)];//识别汉字
NSString *chineseStr = [bStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//转化
string = [string stringByReplacingOccurrencesOfString:bStr withString:chineseStr];//替换
}
}
return string;
}
@end