Created
November 13, 2025 09:08
-
-
Save dterekhov/7f945955de5a96ac50e1e7c7e55f3d9b to your computer and use it in GitHub Desktop.
String+PercentEncodingFormatting: Format a string in a way to use correctly for URLQueryItem #utility #swift-api #real-project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| extension String { | |
| // Encoding for x-www-form-urlencoded | |
| // https://useyourloaf.com/blog/how-to-percent-encode-a-url-string/ | |
| public func addingPercentEncodingForFormData(plusForSpace: Bool = true) -> String? { | |
| let unreserved = "*-._," | |
| var allowed = CharacterSet.alphanumerics | |
| allowed.insert(charactersIn: unreserved) | |
| if plusForSpace { allowed.insert(charactersIn: " ") } | |
| var encoded = self.addingPercentEncoding(withAllowedCharacters: allowed) | |
| if plusForSpace { encoded = encoded?.replacingOccurrences(of: " ", with: "+") } | |
| return encoded | |
| } | |
| } | |
| // Usage example: | |
| /* | |
| var queryItems = | |
| [URLQueryItem(name: "g-recaptcha-response", value: captchaReponse), | |
| URLQueryItem(name: "account[company_name]", | |
| value: signUpRequest.companyName.addingPercentEncodingForFormData()), | |
| URLQueryItem(name: "account[users_attributes][0][time_zone]", | |
| value: signUpRequest.usersAttributes.timeZone), | |
| URLQueryItem(name: "account[users_attributes][0][first_name]", | |
| value: signUpRequest.usersAttributes.firstName | |
| .addingPercentEncodingForFormData()), | |
| URLQueryItem(name: "account[users_attributes][0][last_name]", | |
| value: signUpRequest.usersAttributes.lastName | |
| .addingPercentEncodingForFormData()), | |
| URLQueryItem(name: "account[users_attributes][0][email]", | |
| value: signUpRequest.usersAttributes.email | |
| .addingPercentEncodingForFormData()), | |
| URLQueryItem(name: "account[users_attributes][0][password]", | |
| value: signUpRequest.usersAttributes.password | |
| .addingPercentEncodingForFormData()), | |
| URLQueryItem(name: "account[users_attributes][0][password_confirmation]", | |
| value: signUpRequest.usersAttributes.passwordConfirmation | |
| .addingPercentEncodingForFormData()), | |
| URLQueryItem(name: "account[country]", value: signUpRequest.country), | |
| URLQueryItem(name: "account[time_zone]", value: signUpRequest.timeZone)] | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment