URL encoding is compulsory for building a URL from a string in case it contains special characters.
Why we need URL encoding
From this answer:
A URI is represented as a sequence of characters, not as a sequence of octets. That is because URI might be "transported" by means that are not through a computer network, e.g., printed on paper, read over the radio, etc.
And
For original character sequences that contain non-ASCII characters, however, the situation is more difficult. Internet protocols that transmit octet sequences intended to represent character sequences are expected to provide some way of identifying the charset used, if there might be more than one [RFC2277]. However, there is currently no provision within the generic URI syntax to accomplish this identification. An individual URI scheme may require a single charset, define a default charset, or provide a way to indicate the charset used.
In the IOS SDK we have the following:
User: URLUserAllowedCharacterSet
Password: URLPasswordAllowedCharacterSet
Host: URLHostAllowedCharacterSet
Path: URLPathAllowedCharacterSet
Fragment: URLFragmentAllowedCharacterSet
Query: URLQueryAllowedCharacterSet
You can use addingPercentEncoding(withAllowedCharacters:)
to encode a string correctly.
One important note according to the apple docs for that method:
Entire URL strings cannot be percent-encoded, because each URL component specifies a different set of allowed characters. For example, the query component of a URL allows the “@” character, but that character must be percent-encoded in the password component.
UTF-8 encoding is used to determine the correct percent-encoded characters. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
An example:
let encodedURL = testurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
if let url = URL(string: finalUrl) {
print("valid url")
} else {
print("invalid url")
}
I hope this is helpful.