iOS url出現特殊字元處理 -- stringByAddingPercentEncodingWithAllowedCharacters
阿新 • • 發佈:2018-12-13
stringByAddingPercentEscapesUsingEncoding(只對 `#%^{}[]|\"<> 加空格共14個字元編碼,不包括”&?”等符號), ios9將淘汰,建議用
stringByAddingPercentEncodingWithAllowedCharacters 方法
stringByAddingPercentEncodingWithAllowedCharacters 需要傳一個 NSCharacterSet 物件(關於 NSCharacterSet 這篇 文章說的很好)
如[NSCharacterSet URLQueryAllowedCharacterSet]
URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLHostAllowedCharacterSet "#%/<>[email protected]\^`{|} URLPasswordAllowedCharacterSet "#%/:<>[email protected][\]^`{|} URLPathAllowedCharacterSet"#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>[email protected][\]^`
(2)網路訪問請求:中文空格字元解碼
stringByRemovingPercentEncoding ---- xcode7可能會提示要將stringByAddingPercentEscapesUsingEncoding替換成此方法,要根據是否是解碼來區分
代替 stringByAddingPercentEscapesUsingEncoding
let customAllowedSet = NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet NSString *urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"[email protected]#$^&%*+,:;='\"`<>()[]{}/\\| "] invertedSet]];