swifturlencode

How to URL Encoding in swift



I want to encode url with percent encoding.
If the value of query parameter is url type, how can I encode?
let urlString = "https://www.google.com/path1?param1=https://www.apple.com/path2?param2=asdf"

print(urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))
// https://www.google.com/path1?param1=https://www.apple.com/path2?param2=asdf
// It is not encoded.

I think, my expectation is below.

https://www.google.com/path1?param1=https%3A%2F%2Fwww.apple.com%2Fpath2%3Fparam2%3Dasdf


Solution

  • The idiomatic answer is URLComponents, which is designed to do this percent-encoding for us.

    So consider that you have a well-formed URL, https://www.apple.com/path2?param2=asdf, that you want to pass as param1 to the Google URL. It would be:

    guard var components = URLComponents(string: "https://www.google.com") else {
        return
    }
    
    components.queryItems = [
        URLQueryItem(name: "param1", value: "https://www.apple.com/path2?param2=asdf"),
    ]
    
    guard let url = components.url else {
        return
    }
    
    print(url) // https://www.google.com?param1=https://www.apple.com/path2?param2%3Dasdf
    

    Note: