It is quite common to see that we can correctly set up the HTTP header, token, body and POST/GET methods in our iOS code, but we still can't get the right response. Here is an error which most of people encounter before, incorrect url encoding. Sometimes the error log is not that obvious, which causes developers hours and hours to find the root cause.

Reason why we need to encode URL

With the limitation of system design, URLs can only contain a limited set of characters, and any other characters, such as spaces, brackets, or accented characters, need to be encoded using a special encoding scheme. Some characters, such as the ?, &, #, and = characters, are reserved for specific purposes in URLs, and they need to be encoded if they are used as part of the URL. Encoding the URL ensures that it can be properly interpreted and processed by the server and the client.

In fact, HTTP encoding is part of the standard of HTTP protocol, you can find it here.

Example of encode URL in Swift

Encoding a URL in Swift can be done using the addingPercentEncoding(withAllowedCharacters:) method of the String class, or using the URLEncoding.queryString class of the Foundation framework. It is important to carefully encode the URL to ensure that it is properly transmitted and interpreted, and to avoid any issues or errors. Here is an example:

let originalURLString = "https://www.example.com/search?query=hello world"
let encodedURLString = originalURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
print(encodedURLString) // prints "https://www.example.com/search?query=hello%20world"

In this example, the originalURLString constant is a string that represents an original URL, and the encodedURLString constant is a string that represents the encoded version of the URL.

The addingPercentEncoding(withAllowedCharacters:) method of the String class is used to encode the URL, and the .urlQueryAllowed parameter specifies the allowed characters in the URL. The ! operator is used to force-unwrap the optional result of the method, since the method can return nil if the encoding fails.

The print function is used to print the encoded URL string to the console. The output of the example is the encoded URL string, with the %20 encoding for the space character.

Encoding a URL in Swift can be useful to ensure that the URL can be safely transmitted and interpreted by different systems and devices, and to avoid any issues or errors. It is important to carefully encode the URL to ensure that it is properly transmitted and interpreted, and to avoid any issues or errors.