Add a default header to every URLSession request
Knowing URLSession is configured, not just used.
Set httpAdditionalHeaders on a URLSessionConfiguration, build the session from it, mention per-request overrides win.
Subclassing URLRequest or mutating every request by hand.
WHAT THIS TESTS This question checks whether you know that a URLSession's behavior is driven by its URLSessionConfiguration object rather than by individual requests. Many developers only ever use URLSession.shared, so the interviewer wants to see that you can create and own a configured session.
A GOOD ANSWER COVERS Create a configuration with URLSessionConfiguration.default or .ephemeral. Assign a dictionary to its httpAdditionalHeaders property, for example mapping Authorization to a Bearer token and Accept to application/json. Then construct a session with URLSession(configuration:) and use that session for all calls. Every data task created from it automatically carries those headers, so there is one place to update. Mention that any header set explicitly on an individual URLRequest takes precedence over the session default, which lets you override per call when needed.
COMMON WRONG ANSWERS Saying you would subclass URLRequest, or write a wrapper that mutates each request before sending. Expecting URLSession.shared to somehow hold your custom defaults. Putting the token in httpAdditionalHeaders permanently when it expires, instead of recognizing that short-lived tokens should be injected dynamically.
LIKELY FOLLOW-UPS Where should authentication that refreshes belong instead. The answer is usually an interceptor pattern or building the URLRequest through a small request builder, since httpAdditionalHeaders is captured at session creation. They may ask which headers you should not set here, such as Content-Length, which the system manages.
ONE CONCRETE EXAMPLE You write let config = URLSessionConfiguration.default, then config.httpAdditionalHeaders = ["Authorization": "Bearer abc123", "Accept": "application/json"], then let session = URLSession(configuration: config). Now session.data(from: url) sends both headers without any per-call code. If a single endpoint needs a different Accept value, you set it on that request and it overrides the session-wide default.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.