Swift & iOS

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

~5 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.

How do HTTP caching, ETags, retries, and idempotency work together?

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.

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.

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 migrate a persistent store without losing user data?

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.

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.