The encodings in the various answers here are correct, but you should generally not use .addingPercentEncoding
on an entire URL. As the parameter urlQueryAllowed
notes, that encoding is only appropriate for the query section, not other sections, like the path, host, or authority.
For a hard-coded URL, you can just hand-encode it, but if you're building a URL programmatically, you should use URLComponents:
var components = URLComponents(string: "http://maps.apple.com/")!
components.queryItems = [
URLQueryItem(name: "q", value: "대한민국")
]
// Or, if more convenient:
// components.query = "q=대한민국"
let url = components.url!
This ensures that each piece is encoded correctly, and avoids messy string-interpolation when building URLs programmatically.
As an example of where addingPercentEncoding
goes wrong, consider an IDN domain such as Bücher.example:
let urlString = "https://Bücher.example/?q=대한민국"
print(urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))
// https://B%C3%BCcher.example/?q=%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD
This in incorrect. IDN domains must be encoded in Punycode, not percent-encoding.
var components = URLComponents(string: "http://Bücher.example/")!
components.query = "q=대한민국"
print(components.url!)
// http://xn--bcher-kva.example/?q=%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD