How to properly encode URL in Swift? Problem with Cyrillic and special characters
Hello everyone! I'm new to Swift and encountered a problem when working with URLs. I need to send a GET request to a server with parameters that contain Cyrillic characters and spaces. For example, I form a query string like this:
```swift
let searchText = "Москва центр"
let urlString = "https://api.example.com/search?q=\(searchText)"
let url = URL(string: urlString)
```
But the URL turns out to be nil because the string contains invalid characters. I tried using `addingPercentEncoding(withAllowedCharacters:)`, but I'm not sure which character set to use. I tried `urlQueryAllowed` — Cyrillic gets encoded, but spaces remain. If I use `urlHostAllowed`, everything breaks.
Please advise how to properly and safely encode a URL in Swift? Do I need to encode each parameter separately?
No answers yet.
Log in to leave an answer
Blogs