zoukankan      html  css  js  c++  java
  • 加载图片、视频时,网址中包含中文参数,无法加载数据

           说到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];
    
        }
  • 相关阅读:
    (笔记)ubuntu中取消文件夹或文件等右下解一把锁的标志的方法
    (笔记)Linux常用命令大全
    (笔记)arm-linux-gcc/ld/objcopy/objdump参数总结
    (笔记)Ubuntu下安装arm-linux-gcc-4.4.3.tar.gz (交叉编译环境)
    (笔记)如何安装Arm-linux-gcc
    java application maven项目打自定义zip包
    几种简单的排序算法(JAVA)
    双色球机选算法java实现
    集合的子集输出(位运算方式)
    集合的子集输出(排列组合)
  • 原文地址:https://www.cnblogs.com/linzhengbo/p/5895392.html
Copyright © 2011-2022 走看看