Objective-C
Swift
URL encoding
iOS development
programming languages

Objective-C and Swift URL encoding

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

URL encoding bugs in Apple apps usually come from encoding the wrong part of a request string. Query values, path segments, and form bodies each have different escaping rules, so one universal helper often fails. In both Swift and Objective-C, Foundation APIs can handle this safely when you build URLs from components.

Encode URL Components, Not Entire URL Strings

A request URL has independent parts:

  • Scheme and host.
  • Path segments.
  • Query parameters.

If you percent-encode the full URL string after concatenation, separators such as query delimiters can be escaped incorrectly. Instead, encode only dynamic values at the component level.

Swift: Preferred Pattern with URLComponents

URLComponents and URLQueryItem are the safest default for query strings.

swift
1import Foundation
2
3var components = URLComponents()
4components.scheme = "https"
5components.host = "api.example.com"
6components.path = "/search"
7components.queryItems = [
8    URLQueryItem(name: "q", value: "cats & dogs"),
9    URLQueryItem(name: "city", value: "Tokyo 大阪")
10]
11
12if let url = components.url {
13    print(url.absoluteString)
14}

This avoids manual escaping and produces stable output for Unicode and reserved characters.

Objective-C: Equivalent Foundation Approach

Objective-C uses the same Foundation model.

objective-c
1#import <Foundation/Foundation.h>
2
3NSURLComponents *components = [[NSURLComponents alloc] init];
4components.scheme = @"https";
5components.host = @"api.example.com";
6components.path = @"/search";
7components.queryItems = @[
8    [NSURLQueryItem queryItemWithName:@"q" value:@"cats & dogs"],
9    [NSURLQueryItem queryItemWithName:@"city" value:@"Tokyo 大阪"]
10];
11
12NSLog(@"%@", components.URL.absoluteString);

If your app supports both Swift and Objective-C code paths, using this shared pattern reduces cross-language inconsistencies.

Path Segment Encoding Requires Different Allowed Characters

Path segment input should not be encoded with query rules. For example, slash in user input can change path structure if not escaped.

swift
1import Foundation
2
3let raw = "2026/report draft"
4let allowed = CharacterSet.urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))
5let encoded = raw.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
6
7let url = "https://api.example.com/files/\(encoded)"
8print(url)

This keeps user value in one segment instead of creating accidental nested paths.

Form Body Encoding Is Not the Same as Query Encoding

For application/x-www-form-urlencoded requests, space handling often differs from standard URL query construction. Some servers expect space represented as plus in form bodies.

swift
1import Foundation
2
3func formEncode(_ value: String) -> String {
4    let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._* "))
5    let escaped = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
6    return escaped.replacingOccurrences(of: " ", with: "+")
7}
8
9let body = "q=\(formEncode("cats & dogs"))&lang=\(formEncode("en-US"))"
10print(body)

Use this only when your networking layer does not already encode forms.

Avoid Double Encoding

Double encoding is a frequent production issue, especially when middleware and request builders both attempt escaping.

Typical symptom is repeated percent markers in output. Prevention strategy:

  • Keep raw values in domain models.
  • Encode once at request-boundary layer.
  • Do not re-encode values passed from an already encoded helper.

A dedicated network utility module helps enforce this rule.

Testing URL Encoding Behavior

Unit tests should include edge inputs:

  • Spaces and plus signs.
  • Ampersand and equals in values.
  • Unicode characters.
  • Slash in path values.

Validate both:

  • Outbound URL string.
  • Server-decoded value.

A URL can look correct while still decoding incorrectly on backend parsers.

Common Pitfalls

  • Encoding a fully assembled URL string. Fix by encoding only dynamic component values.
  • Using query rules for path segments. Fix by using path-safe character sets and escaping slash when necessary.
  • Confusing form-body encoding with query encoding. Fix by handling form payloads with form-specific rules.
  • Applying encoding multiple times across networking layers. Fix by centralizing encoding responsibilities.
  • Skipping Unicode test cases. Fix by adding multilingual and reserved-character inputs in tests.

Summary

  • URL encoding in Swift and Objective-C is safest with component-based Foundation APIs.
  • Use URLComponents and query items for query parameter construction.
  • Treat path segments and form bodies as separate encoding problems.
  • Encode once at the request boundary to avoid double-encoding bugs.
  • Add realistic tests for reserved characters and Unicode values.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.