网络请求报错 code = 1002 处理
[toc]
错误异常
今天使用URLsection写了个文件下载请求,写完后运行程序报错,如下
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" **
*Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fa9b1d06120 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}} *
错误原因
后来百度了一下是URL编码问题,只要报请求url用utf-8转码一下就可以了
处理方法
iOS 8 要用utf8转码:
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iOS 8 以后要用这个方法:
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
or
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];