How to properly URL encode in Swift for iOS?
Hello everyone! I'm a beginner in Swift and iOS development, and I'm having a problem with URL encoding. I need to send a GET request to an API that accepts parameters in the query string. One of the parameters is a string with Cyrillic characters and special characters (for example, "Привет, мир! & тест").\n\nI tried using `addingPercentEncoding(withAllowedCharacters:)`, but it's not working. Here's the code I wrote:\n\n```swift\nlet baseURL = "https://api.example.com/search"\nlet query = "Привет, мир! & тест"\nlet encodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)\nlet fullURL = "\\(baseURL)?q=\\(encodedQuery)"\nprint(fullURL)\n```\n\nBut in the console, I see that spaces turn into `%20`, while the `&` character remains as is. Because of this, the server incorrectly parses the request.
No answers yet.
Log in to leave an answer