加载图片、视频时,网址中包含中文参数,无法加载数据

       说到URL包含中文字段这个问题,我们必须要知道NSURL在初始化一个实例对象时,如: [NSURL URLWithString:url] 或 

 

[NSURL fileURLWithPath:path];返回的nsurl对象为nil或是对象的链接是乱码。

 

 

 

 

网址示例:

NSString *urlstr = @"http://odqaqbbj4.bkt.clouddn.com/pic_中文字段_20160921191844";

对网址进行转码

NSString *url = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];

加载图片

[cell.imgView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"adPlaceholder"]];

就OK了。

 

我是在使用sdwebimage加载图片时,遇到的这个问题。转码过程中的@"`#%^{}\"[]|\\<> "这一部分我是在网上看到的,至于为什么是这样,我也不是很明白,具体可参考这篇博客:http://www.aichengxu.com/view/82953。

 

加载网络视频时,如果URL有中文字段,

    NSCharacterSet *encodeSet = [NSCharacterSet URLQueryAllowedCharacterSet];

    NSString *encodeUrl = [urlString stringByAddingPercentEncodingWithAllowedCharacters:encodeSet];

    NSURL *URL= [NSURL URLWithString:encodeUrl];

 

(1) 网络访问请求:中文空格字符编码/解码

        stringByAddingPercentEscapesUsingEncoding(只对 `#%^{}[]|\"<> 加空格共14个字符编码,不包括”&?”等符号), ios9将淘汰,建议用stringByAddingPercentEncodingWithAllowedCharacters方法

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}

        URLHostAllowedCharacterSet      "#%/<>?@\^`{|}

        URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}

        URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}

        URLQueryAllowedCharacterSet     "#%<>[\]^`{|}

        URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

(2)网络访问请求:中文空格字符解码

        stringByRemovingPercentEncoding  ----  xcode7可能会提示要将stringByAddingPercentEscapesUsingEncoding替换成此方法,要根据是否是解码来区分

        */
        //代替stringByAddingPercentEscapesUsingEncoding

        let customAllowedSet =  NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet
NSString * resourcePath = @"https://www.xiaocaobank.com";
  
    NSString *encodePath ;
    
    if (!IOS7_OR_LATER) {
        encodePath = [resourcePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        encodePath = [resourcePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];

    }

转载于:https://www.cnblogs.com/linzhengbo/p/5895392.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值