Read about what ‘addingPercentEncoding
‘ is and why it’s important in URL handling.
addingPercentEncoding(withAllowedCharacters:)
is a String method in Swift that encodes special characters in a string to make it URL-safe. This is often called “URL encoding” or “percent encoding.”
Let me break this down with examples:
// Example 1: Basic city name encoding
let city = "New York"
let encoded = city.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(encoded) // Outputs: "New%20York"
// Example 2: More complex string with special characters
let location = "São Paulo, Brazil"
let encoded2 = location.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(encoded2) // Outputs: "S%C3%A3o%20Paulo%2C%20Brazil"
// Example 3: String with various special characters
let searchQuery = "Weather in Paris & London"
let encoded3 = searchQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(encoded3) // Outputs: "Weather%20in%20Paris%20%26%20London"
Why URL encoding is necessary?
- URLs can only contain certain characters (ASCII characters)
- Spaces and special characters need to be encoded to be valid in a URL
- Without encoding, the URL might break or behave unexpectedly
Common character encodings:
- Space becomes
%20
- , (comma) becomes
%2C
- & becomes
%26
- á becomes
%C3%A1
- @ becomes
%40
Here’s a practical example showing why it’s important:
class WeatherService {
func createWeatherURL(for city: String) -> URL? {
// BAD: Without encoding
let badURL = "https://api.weather.com/data?city=\(city)"
// GOOD: With encoding
guard let encodedCity = city.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return nil
}
let goodURL = "https://api.weather.com/data?city=\(encodedCity)"
// Example usage:
let cityName = "New York"
print("Bad URL: \(badURL)") // https://api.weather.com/data?city=New York (Invalid URL!)
print("Good URL: \(goodURL)") // https://api.weather.com/data?city=New%20York (Valid URL)
return URL(string: goodURL)
}
}
Different character sets you can use for URL encoding:
let example = “Test String!”
print(example.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)) :- For host names
print(example.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)) :- For URL paths
print(example.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) :- For query parameters
print(example.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)) :- For URL fragments
Common mistakes to avoid:
class WeatherService {
func fetchWeather() {
// MISTAKE 1: Not encoding the city name
let city = "New York"
let badURL = URL(string: "https://api.weather.com?city=\(city)") // This might fail
// MISTAKE 2: Double encoding
let encodedOnce = city.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let encodedTwice = encodedOnce?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
// Don't do this! It will encode the % symbols again
// CORRECT USAGE
guard let encodedCity = city.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: "https://api.weather.com?city=\(encodedCity)") else {
print("Invalid URL")
return
}
// Now url is safe to use
}
}
To decode an encoded string:
let encodedString = "New%20York"
if let decodedString = encodedString.removingPercentEncoding {
print(decodedString) // Outputs: "New York"
}
This encoding is particularly important when:
- Handling user input that goes into URLs
- Working with international characters
- Creating query parameters that contain special characters
- Building URLs dynamically
Remember: Always encode parameters before adding them to URLs, but don’t encode the entire URL string – only encode the parts that need it (like query parameters, path components, etc.).
Thanks for reading!