Send Query Values Without Losing Plus Signs
Someone searches for C++ & Swift. Your app constructs a URL, sends it, and gets results for something closer to C & Swift.
The networking layer has quietly edited their choice of programming language.
This can happen even when URLComponents returns the original query value in a local test. The missing check is what the server’s query parser does with it. We’ll build a small request helper and test the receiving side, including plus signs, percent sequences, repeated filters, and characters that could otherwise become extra parameters.
The example uses established Foundation APIs, checked with Xcode 27.2 and Swift 6.4.2. The complete sample targets iOS 17 and macOS 14; this is a current interoperability problem, not a new OS feature.
Agree on what the receiver decodes
A literal + is allowed in a URL query. Apple’s queryItems documentation explicitly warns that another implementation may interpret it as a space.
The form-style parsing algorithm replaces literal plus signs with spaces before percent-decoding. That order matters:
| Encoded query value | Value after form-style decoding |
|---|---|
a+b | a b |
a%20b | a b |
a%2Bb | a+b |
%252B | The literal text %2B |
Our search endpoint uses that form-style decoder. Confirm your endpoint’s behavior before applying this policy. URL query syntax alone does not require every backend, deep link, or signature verifier to interpret a value this way.
Swift Unwrap’s phone-number example illustrates the same problem with an international dialing prefix. The Stack Overflow question about encoding plus signs already has an accepted solution, including the targeted adjustment we’ll use. The extra work here is making the request boundary explicit and proving the receiving side preserves the values.
Give Foundation the raw values first
Use URLQueryItem for the names and values. Let Foundation escape characters such as &, = and % in those components. Then replace literal + characters in its already encoded query with %2B.
Put the following Swift blocks in one file, in order:
import Foundation
nonisolated enum QueryURLFailure: Error {
case cannotDecomposeEndpoint
case cannotBuildURL
}
nonisolated func replacingQueryForFormDecoder(
on endpoint: URL,
with items: [URLQueryItem]
) throws -> URL {
guard var components = URLComponents(
url: endpoint,
resolvingAgainstBaseURL: true
) else {
throw QueryURLFailure.cannotDecomposeEndpoint
}
components.queryItems = items.isEmpty ? nil : items
components.percentEncodedQuery = components.percentEncodedQuery?
.replacingOccurrences(of: "+", with: "%2B")
guard let url = components.url else {
throw QueryURLFailure.cannotBuildURL
}
return url
}
This follows the post-encoding approach in Martin R’s accepted answer. It changes one specific representation after Foundation has handled the individual components.
The helper deliberately replaces the endpoint’s query. An empty item array removes it. Supply an app-owned endpoint and the complete desired item list; don’t use this to rewrite an existing signed URL. Changing the query’s bytes or parameters can invalidate its signature.
percentEncodedQuery expects correctly encoded text. Its setter can fail fatally for malformed escapes. Here, the source comes from Foundation’s own encoder, and the only adjustment introduces a valid escape. Don’t replace that source with untrusted, supposedly pre-encoded text.
The nonisolated declarations keep the synchronous helper usable under MainActor-default isolation with the current compiler. They don’t create a background task.
Keep repeated filters and literal percent sequences
Build the request from an array, rather than a dictionary that cannot represent repeated names:
nonisolated func makeSearchRequest(
endpoint: URL,
term: String,
topics: [String]
) throws -> URLRequest {
let items = [URLQueryItem(name: "q", value: term)]
+ topics.map { URLQueryItem(name: "topic", value: $0) }
let url = try replacingQueryForFormDecoder(
on: endpoint,
with: items
)
var request = URLRequest(url: url)
request.httpMethod = "GET"
return request
}
nonisolated func exampleSearchRequest() throws -> URLRequest {
let endpoint = URL(string: "https://example.com/search")!
return try makeSearchRequest(
endpoint: endpoint,
term: "C++ & Swift",
topics: ["iOS", "C++"]
)
}
The example builds a request; it doesn’t send anything to example.com. Pass your real endpoint and the resulting URLRequest to your existing networking layer. Its encoded query is:
q=C%2B%2B%20%26%20Swift&topic=iOS&topic=C%2B%2B
The server should receive q as C++ & Swift and two topic pairs, in the supplied order. Apple’s query-items contract permits repeated names; your service decides what repeated filters mean.
Always pass raw text. If the person actually types %2B, the encoded value must be %252B. After one decoding pass, the receiver gets the original three characters. That is correct encoding, not an error to repair by decoding again.
Conversely, pre-encoding a real + to %2B and then supplying it to URLQueryItem asks Foundation to preserve a literal percent sequence. The receiver gets %2B, not +. Don’t make the server decode repeatedly until the result looks plausible.
This helper builds a GET query. It is not a complete application/x-www-form-urlencoded body serializer or a canonical representation for request signing. Those formats have their own requirements. It also doesn’t decide which input characters your service permits; preserving text and validating it are separate jobs.
Test a different parser, not only a round trip
A Foundation-only test can miss the original bug:
- Put the raw term in
queryItems, without the plus adjustment. - Construct the URL.
- Read it back using
URLComponents.queryItems. - Observe the original
C++ & Swiftand declare success.
That proves two Foundation operations agree. A form-style receiver still sees three spaces after C: two from the plus signs and one from the original space.
The downloadable sample sends real URLSession requests to a disposable loopback server. The server returns the raw request target and a list produced by Python’s parse_qsl, configured to retain blank values. That parser is independent of the Swift helper. The fixture keeps repeated pairs instead of converting them into a dictionary.
On an Apple Silicon Mac with Xcode 27.2 selected and Python 3 installed, run python3 verify.py from the extracted sample. Add --ios to run the native client with the iOS 27.2 simulator runtime; the included README explains both paths.
The checks compare decoded values with the original UTF-8 bytes, including decomposed accents and emoji. They also inspect the wire representation and the number of received parameters:
| Input or condition | What must survive |
|---|---|
C++ & Swift | Both plus signs, the ampersand and spaces |
literal%2B | Literal percent text after exactly one decode |
x&admin=true | One value, not an additional admin parameter |
a=b, #section, ?next=/docs | Text inside the value |
Two topic items | Two ordered pairs |
| An empty search term | A present q pair with an empty value |
| Existing endpoint query | Replaced by the supplied complete list |
Negative controls omit the plus adjustment, pre-encode a value, and manually assemble values with .urlQueryAllowed. The last can leave & and = as query syntax. Each demonstrates a different failure; none is a recommended alternative.
This follows the same principle as our real-transport cookie tests: test the layer responsible for the promise. The Python fixture needs no production backend or credentials and binds only to the local machine. Its behavior establishes this parser contract, not every server framework’s duplicate-key, input-validation, or signature rules. Add a matching integration case against your actual service.
Verification: both Swift blocks compile with Xcode 27.2 / Swift 6.4.2, Swift 6 warnings as errors, and iOS 17 / macOS 14 deployment targets. The checks passed on macOS 27.2 and a native iOS 27.2 simulator in ordinary and MainActor-default isolation: 28 real requests per mode, including the three failing approaches above. The older deployment targets are compile checks; this does not claim older-runtime, physical-device, or production-service verification.