URLString里含有中文或者特殊字符导致NSURL为空

对于已经上线的项目里面,如果图片链接里含有有中文或者特殊字符,图片就会显示不出来,为NSURL添加一个分类,就可以解决

.m

#import "NSURL+Hook.h"
#import <objc/runtime.h>


@implementation NSURL (Hook)

+(void)load{
    
    //本方法编译时执行
    //得到函数URLWithString:的指针
    Method urlWithStringMethod = class_getClassMethod([NSURL class], NSSelectorFromString(@"URLWithString:"));
    //得到函数SJCURLWithString:的指针(C方法)
    Method SJCURLWithString = class_getClassMethod([NSURL class], sel_registerName("SJCURLWithString:"));
    //交换两个函数的指针,这样,当调用函数URLWithString时就会执行SJCURLWithString。
    method_exchangeImplementations(urlWithStringMethod, SJCURLWithString);
}


+(instancetype)SJCURLWithString:(NSString *)URLString{
    
    if (URLString && [URLString isKindOfClass:[NSString class]] && URLString.length > 0) {
        
        //因为函数的指针已经交换,所以这里想要调用函数URLWithString:,则需要调用SJCURLWithString:。
        NSURL * url = [NSURL SJCURLWithString:URLString];
        if (url) {
            
            return url;
        }else{
            
            NSURL * url = [NSURL SJCURLWithString:(NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)URLString, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8))];
            return url;
        }
    }
    else{
        
        NSLog(@"异常:地址为空");
        NSURL * url = [NSURL SJCURLWithString:@"https://www.baidu.com"];
        return url;
    }
}

@end

1.stringByAddingPercentEscapesUsingEncoding,功能不完善(9.0过期一般含中文就足够可以处理了)(只对 `#%^{}[]|"<> 加空格共14个字符编码,不包括”&?”等符号)
2.stringByAddingPercentEncodingWithAllowedCharacters,当含有%时又会转义回去([NSCharacterSet URLFragmentAllowedCharacterSet];[NSCharacterSet characterSetWithCharactersInString:@"!$&'()*+,-./:;=?@_~%#[]"].invertedSet)
3.CFURLCreateStringByAddingPercentEscapes, 推荐使用这个函数
当含有/,%这些字符又有中文时,中文会被转成Unicode编码,但是已经被转义成Unicode编码不会被再次转义

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、问题背景 相信很多ios开发者在项目中都需要用到uiwebview,那就离不开url了,一般符合网络标准的...
    FuWees阅读 7,089评论 1 6
  • 前言 最先接触编程的知识是在大学里面,大学里面学了一些基础的知识,c语言,java语言,单片机的汇编语言等;大学毕...
    oceanfive阅读 3,150评论 0 7
  • 字符是用户可以读写的最小单位。计算机所能支持的字符组成的集合,就叫做字符集。字符集通常以二维表的形式存在。二维表的...
    刘惜有阅读 8,197评论 2 14
  • 多久前透过琉璃的月光, 俯首间沾染, 是白发的感伤。
    北原遇福泽阅读 243评论 2 5
  • 答应为赵先生的私人基金会工作之前,我对他所知甚少: 身高1米91, 习练南拳多年, 因在内蒙古的鄂伦春文化保护项目...
    山女画眉鸟阅读 428评论 0 1