在iOS请求中经常会出现链接中带有特殊字符或者中文的情况,这时候链接String转URL的时候就会出现问题,你会发现最后得到的URL是空值,但是这并不是我们想要的,所以这时候就需要对请求的链接做一些处理,转换成可以被转为URL的String
OC:
NSString *charactersToEscape =@"`#%^{}\"[]|\\<> ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *<最终结果的String> = [<需要转换的请求String> stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
Swift:
let charactersToEscape = "`#%^{}\"[]|\\<> ";
let allowedCharacters :CharacterSet = CharacterSet.init(charactersIn: charactersToEscape).inverted
let <最终结果的String> = <需要转换的请求String>.addingPercentEncoding(withAllowedCharacters: allowedCharacters)