How do I URL encode a string

前端 未结 22 1705
轮回少年
轮回少年 2020-11-22 07:16

I have a URL string (NSString) with spaces and & characters. How do I url encode the entire string (including the & ampersand

22条回答
  •  灰色年华
    2020-11-22 08:11

    Here's a production-ready flexible approach in Swift 5.x:

    public extension CharacterSet {
    
        static let urlQueryParameterAllowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&?"))
    
        static let urlQueryDenied           = CharacterSet.urlQueryAllowed.inverted()
        static let urlQueryKeyValueDenied   = CharacterSet.urlQueryParameterAllowed.inverted()
        static let urlPathDenied            = CharacterSet.urlPathAllowed.inverted()
        static let urlFragmentDenied        = CharacterSet.urlFragmentAllowed.inverted()
        static let urlHostDenied            = CharacterSet.urlHostAllowed.inverted()
    
        static let urlDenied                = CharacterSet.urlQueryDenied
            .union(.urlQueryKeyValueDenied)
            .union(.urlPathDenied)
            .union(.urlFragmentDenied)
            .union(.urlHostDenied)
    
    
        func inverted() -> CharacterSet {
            var copy = self
            copy.invert()
            return copy
        }
    }
    
    
    
    public extension String {
        func urlEncoded(denying deniedCharacters: CharacterSet = .urlDenied) -> String? {
            return addingPercentEncoding(withAllowedCharacters: deniedCharacters.inverted())
        }
    }
    

    Example usage:

    print("Hello, World!".urlEncoded()!)
    print("You&Me?".urlEncoded()!)
    print("#Blessed 100%".urlEncoded()!)
    print("Pride and Prejudice".urlEncoded(denying: .uppercaseLetters)!)
    

    Output:

    Hello,%20World!
    You%26Me%3F
    %23Blessed%20100%25
    %50ride and %50rejudice
    

提交回复
热议问题