美文网首页
iOS URL带特殊字符(汉字、空格等)导致图片加载失败

iOS URL带特殊字符(汉字、空格等)导致图片加载失败

作者: 马威明 | 来源:发表于2019-02-27 16:59 被阅读0次
部分特殊字符编码

在加载网络图片(特别是使用SDWebImage加载图片)时,我们经常会遇到图片缓存失败的情况,打印url后我们会发现 字符串中总会有一些不合法的字符(汉字、空格等).
所以加载图片时要考虑到url处理的问题.
通常情况下,新建一个NSURL的分类重载+ (void)load方法,采用runtime动态交换方法是最常用的选择.

+ (void)load {
   // 获取URLWithString:方法的地址
   Method URLWithStringMethod = class_getClassMethod(self, @selector(URLWithString:));
   // 获取BMW_URLWithString:方法的地址
   Method BMW_URLWithStringMethod = class_getClassMethod(self, @selector(BMW_URLWithString:));
   // 交换方法地址
   method_exchangeImplementations(URLWithStringMethod, BMW_URLWithStringMethod);
   
}
+ (NSURL *)BMW_URLWithString:(NSString *)URLString {
   NSString *newURLString = [self isChinese:URLString];
   return [NSURL BMW_URLWithString:newURLString];
}
//处理特殊字符
+ (NSString *)isChinese:(NSString *)str {
   NSString *newString = str;
   //遍历字符串中的字符
   for(int i=0; i< [str length];i++){
       int a = [str characterAtIndex:i];
       //汉字的处理
       if( a > 0x4e00 && a < 0x9fff)
       {
           NSString *oldString = [str substringWithRange:NSMakeRange(i, 1)];
           NSString *string = [oldString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
           newString = [newString stringByReplacingOccurrencesOfString:oldString withString:string];
       }
       //空格处理
       if ([newString containsString:@" "]) {
           newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

       }
     //如果需要处理其它特殊字符,在这里继续判断处理即可.
   }
   return newString;
}

实现以上方法后 调用URLWithString加载数据时,会自动处理汉字和空格,如果需要处理其它特殊字符,只需要在方法后面加上判断继续处理就行了.

相关文章

网友评论

      本文标题:iOS URL带特殊字符(汉字、空格等)导致图片加载失败

      本文链接:https://www.haomeiwen.com/subject/hopfuqtx.html