url的编码与解码,在工程中很常用,编解码针对特殊字符及中文,确保url可以正常访问

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20

let KUrlCodingReservedCharacters = "!*'();:|@&=+$,/?%#[]{}"

extension NSString {
    
    /// url编码
    ///
    /// - Returns: NSString
    func urlEncode() -> NSString? {
        return self.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: KYKUrlCodingReservedCharacters).inverted)! as NSString
        
    }
    
    /// url解码
    ///
    /// - Returns: NSString
    func urlDecode() -> NSString? {
        return self.removingPercentEncoding as NSString?
    }
}