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


           说到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];
    
        }
  • 相关阅读:
    调用API接口,查询手机号码归属地(2)
    调用API接口,查询手机号码归属地(1)
    F
    Icebound and Sequence(非互质逆元 快速乘法)or(矩阵快速幂)
    ProblemC、小花梨判连通(dfs)+想法stl
    cwb个人练习
    Fire Net (二分图匹配 匈牙利算法模板)
    Fire Net HDU
    Going Home POJ
    Two Sequences (二分+二进制) (好题)
  • 原文地址:https://www.cnblogs.com/linzhengbo/p/5895392.html
Copyright © 2020-2023  润新知