说到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]; }