加載圖片、視頻時,網址中包含中文參數,沒法加載數據

       說到URL包含中文字段這個問題,咱們必需要知道NSURL在初始化一個實例對象時,如: [NSURL URLWithString:url] 或 ios

 

[NSURL fileURLWithPath:path];返回的nsurl對象爲nil或是對象的連接是亂碼。web

 

 

 

 

網址示例:xcode

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

對網址進行轉碼編碼

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

加載圖片spa

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

就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];

    }
相關文章
相關標籤/搜索