Swift & iOS

Design networking, authentication, TLS, token refresh, persistence, and failure handling for mobile applications.

~8 min reading
Suggest content

Networking, Security, and Data

🟪 Syntax · 🟦 Types/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Gotcha · 🧠 Explanation

Networking layer responsibilities

A maintainable networking flow separates concerns:

TEXT
Endpoint/Request Builder
  -> HTTP Client
  -> Response Validation
  -> DTO Decoding
  -> Mapping
  -> Repository
  -> Domain/Presentation

Distinguish these failures:

  • Connectivity and timeout
  • Cancellation
  • Invalid HTTP response
  • Authentication/authorization
  • Server error
  • Decoding/schema mismatch
  • Business-rule rejection

Do not collapse every error into a generic message too early. Preserve typed errors internally, then map them to user-facing view data at the presentation boundary.

What makes retrying an HTTP operation safe?

Short answer: Retry only failures covered by a bounded retry policy, and preserve the same logical operation identity when the server supports deduplication. A timeout does not prove a write was never processed, so a retry can otherwise repeat its effect. Cache validation reduces unnecessary reads, but is a separate contract from safely repeating writes.

Detailed explanation:

Use HTTP cache directives and validators such as ETags to reuse or revalidate responses according to server policy. Retry only transient failures with bounded exponential backoff and jitter; respect Retry-After. A timeout does not prove the server did not process a write, so retry a mutation only when its semantics are idempotent or the API supports an idempotency key. Keep authentication and validation errors out of blind retry loops, and make cancellation stop client-side waiting where possible.

🟦 Illustrative example:

HTTP
GET /accounts/summary HTTP/1.1
Host: api.example.com
If-None-Match: "summary-v7"
​
HTTP/1.1 304 Not Modified
ETag: "summary-v7"
Cache-Control: private, max-age=0, must-revalidate

🧠 The client reuses its matching cached representation after revalidation; 304 has no replacement representation body. This read-cache exchange is separate from write deduplication: retries of one logical payment need the same persisted operation key under an explicit server idempotency contract. Do not cache sensitive account data without an account-scoped storage and logout policy. HTTP conditional response semantics.

API-backed dynamic list

Minimum behavior:

  • idle, loading, loaded, empty, and failed states
  • Cancellation when the screen disappears or the query changes
  • Main-actor UI updates
  • Pagination guards
  • Retry support
  • DTO-to-domain mapping
  • Dependency-injected repository for testing

@Published informs observers when the state changes. It does not make an API realtime by itself. Realtime behavior requires polling, server push, WebSocket, notifications, or another source that emits new values.

Authentication and token refresh

A robust design uses a single refresh coordinator, often an actor:

  1. Send the request with the current access token.
  2. If it fails because the token expired, join an existing refresh operation or start one.
  3. Update tokens atomically.
  4. Retry eligible requests once.
  5. If refresh fails, clear the authenticated session and transition to login.

Avoid allowing every failed request to launch its own refresh request. That creates races, token overwrites, and unnecessary load.

Store secrets in Keychain, not UserDefaults. Avoid logging credentials, tokens, full sensitive responses, or personal data.

TLS and SSL pinning

TLS normally verifies that the server certificate chains to a trusted certificate authority and matches the requested host. Pinning adds an application-controlled requirement: the certificate or public key must also match a known pin.

Pinning can reduce exposure to compromised certificate authorities or certain interception scenarios, but it adds operational risk.

🟦 Worked example: What does SSL pinning add? explains the TLS handshake, leaf/CA public-key versus whole-certificate pins, Apple's declarative ATS configuration, a Swift URLSession implementation, and a rotation/failure checklist. Keep the detailed code in that canonical answer.

Pinning is an additional restriction, not a replacement for normal certificate-chain and hostname validation. Most apps can rely on platform TLS trust; Apple recommends pinning only when a specific requirement justifies its operational cost. “SSL pinning” is the common legacy name; modern connections use TLS.

Certificate pinning versus public-key pinning

  • Certificate pinning matches a particular certificate and usually changes when the certificate is renewed.
  • Public-key pinning matches the key material and can survive certificate renewal when the key remains the same.

Safe rotation plan

  • Ship at least one active pin and a tested backup pin.
  • Add future pins before the backend rotation.
  • Rotate the server only after the updated application has sufficient adoption.
  • Keep an emergency release process.
  • Monitor trust failures separately from general networking errors.
  • Test production-like certificate chains before release.
  • Coordinate mobile and backend ownership.

A remote flag cannot safely repair a pinning failure if the app cannot establish the trusted connection required to download that flag.

Alamofire concept

Alamofire uses a ServerTrustManager with host-specific trust evaluators. The evaluator should be limited to intended hosts and should still perform normal host/default validation where appropriate. Treat DisabledTrustEvaluator as a development-only tool, never a production fix.

Data persistence choices

NeedAppropriate choice
Small preferences and flagsUserDefaults
Passwords, tokens, keysKeychain
Images or document blobsFile system/cache directories
Structured relational/offline dataCore Data or SwiftData
Temporary in-memory reuseNSCache or actor-protected cache

Choose based on data sensitivity, size, query requirements, lifetime, migration, synchronization, and offline behavior.

How do you change a stored-data schema without losing user data?

Short answer: Use a versioned migration that transforms real old data into the new schema and has a defined failure or recovery path. Test interrupted upgrades and realistic existing stores before rolling it out. Deleting and recreating the user's store is not a normal migration strategy because it discards the data the upgrade should preserve.

Detailed explanation:

Treat schema migration as a release and recovery problem. Define versioned, tested migrations; preserve a backup or a safe recovery path where the framework and product allow it; test realistic old stores and interrupted upgrades; and make the new app tolerate server/client version skew. Roll out incrementally and monitor migration failures. Do not delete a user's store and recreate it as a routine response to a migration error.

🟦 Illustrative example:

SQL
BEGIN;
ALTER TABLE pending_orders ADD COLUMN currency_code TEXT;
UPDATE pending_orders SET currency_code = 'TRY'
WHERE currency_code IS NULL AND legacy_currency = 'TRY';
PRAGMA user_version = 2;
COMMIT;

🧠 This illustrative SQLite migration expands the schema and maps only records whose old currency is known; it does not invent a currency for unknown records or drop pending writes. The migration runner must check the old version, verify every required row, roll back on failure, and test restart/low-space behavior. A Core Data or SwiftData application uses its framework migration APIs rather than running this SQL against framework-owned storage.

URL construction and correction

  • Prefer URLComponents and URLQueryItem over manual string concatenation.
  • Percent-encode components, not an entire already-structured URL blindly.
  • Validate schemes and hosts for external links.
  • Do not silently convert arbitrary user input into a trusted URL.
SWIFT
var components = URLComponents()
components.scheme = "https"
components.host = "api.example.com"
components.path = "/search"
components.queryItems = [URLQueryItem(name: "query", value: searchText)]
let url = components.url

Physical iPhone location during development

An application running on a connected physical iPhone normally obtains location from the iPhone's Core Location services, not from the Mac's location setting. Xcode can simulate locations during debugging, so verify the active run scheme and location simulation. The simulator uses simulated or Mac-provided data depending on configuration.

This is mainly an environment/debugging topic rather than a core interview topic.

Apple ecosystem Wi-Fi sharing

Known Wi-Fi credentials can synchronize through iCloud Keychain across devices using the same Apple Account. Disabling synchronization has privacy and convenience tradeoffs and is not an iOS engineering interview priority. Keep this thread separate from application architecture and networking-security answers.