🍎 Swift & iOS Intermediate

What is NSURLSession and networking in iOS?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

URLSession (NSURLSession in Objective-C) is the modern networking API for iOS apps — handles HTTP/HTTPS, caching, cookies, authentication, background downloads. Basic GET request: struct APIClient { let session = URLSession.shared func fetchUsers() async throws -> [User] { let url = URL(string: "https://api.example.com/users")! var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let (data, response) = try await session.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { throw URLError(.badServerResponse) } guard (200...299).contains(httpResponse.statusCode) else { throw APIError.httpError(httpResponse.statusCode) } return try JSONDecoder().decode([User].self, from: data) } }. POST with body: request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try JSONEncoder().encode(newUser) let (data, response) = try await session.data(for: request). URLSession configurations: .default (uses disk cache, credentials), .ephemeral (no cache/cookies — private browsing), .background (transfers continue when app suspended). Codable for JSON: struct User: Codable { let id: Int let name: String let email: String } let users = try JSONDecoder().decode([User].self, from: data) let json = try JSONEncoder().encode(user). async/await vs completion handlers: async/await is the modern approach (iOS 15+); completion handlers for older targets. Third-party: Alamofire (feature-rich networking layer), Moya (type-safe networking), Apollo (GraphQL).

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Swift & iOS answers easy to follow.