欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS url出现特殊字符处理 -- stringByAddingPercentEncodingWithAllowedCharacters

程序员文章站 2023-01-13 20:16:25
stringByAddingPercentEscapesUsingEncoding(只对 `#%^{}[]|\"<> 加空格共14个字符编码,不包括”&?”等符号), ios9将淘汰,建议用 stringByAddingPercentEncodingWithAllowedCharacters 方法 ......
stringbyaddingpercentescapesusingencoding(只对 `#%^{}[]|\"<> 加空格共14个字符编码,不包括”&?”等符号), ios9将淘汰,建议用 stringbyaddingpercentencodingwithallowedcharacters 方法

stringbyaddingpercentencodingwithallowedcharacters  需要传一个  nscharacterset  对象(关于  nscharacterset  文章说的很好)

如[nscharacterset  urlqueryallowedcharacterset]

urlfragmentallowedcharacterset  "#%<>[\]^`{|}

urlhostallowedcharacterset      "#%/<>?@\^`{|}

urlpasswordallowedcharacterset  "#%/:<>?@[\]^`{|}

urlpathallowedcharacterset      "#%;<>?[\]^`{|}

urlqueryallowedcharacterset    "#%<>[\]^`{|}

urluserallowedcharacterset      "#%/:<>?@[\]^`

(2)网络访问请求:中文空格字符解码

stringbyremovingpercentencoding  ----  xcode7可能会提示要将stringbyaddingpercentescapesusingencoding替换成此方法,要根据是否是解码来区分

代替  stringbyaddingpercentescapesusingencoding

let customallowedset =  nscharacterset(charactersinstring:"`#%^{}\"[]|\\<> ").invertedset

nsstring *urlstr = [urlstr stringbyaddingpercentencodingwithallowedcharacters:[[nscharacterset charactersetwithcharactersinstring:@"?!@#$^&%*+,:;='\"`<>()[]{}/\\| "] invertedset]];