This one is about a lint rule I wrote for an iOS app that sends credentials to self-hosted servers, and about how URLSession picks the method that handles a redirect, which it does by Objective-C selector and not by the Swift name the rule was looking for.
The setup is simple enough. When a server answers with a 302, URLSession asks the task’s delegate whether to follow it, through this method:
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void
)
Whoever implements it decides whether the Authorization header goes along to the new host, so the idea was to let exactly one file declare it, with a swift-syntax rule that fails the build when any other file does. The first version of the rule looked for a function with the base name urlSession and those labels and parameter types, which is how you’d describe the method if you only ever read Swift.
URLSession doesn’t know the Swift name
URLSession is an Objective-C class, and it finds the delegate method the Objective-C way, by asking the delegate whether it responds to a selector:
URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
The Swift name urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) is just how that selector is imported. Anything that ends up in the Objective-C runtime under that selector gets the call, whatever it’s called in Swift, and the easiest way to get there is an explicit @objc name:
final class RenamedRedirectHandler: NSObject, URLSessionDelegate {
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func followRedirect(
_: URLSession,
_: URLSessionTask,
_: HTTPURLResponse,
_: URLRequest,
_ completionHandler: @escaping (URLRequest?) -> Void
) {
completionHandler(nil)
}
}
I first left this shape out, because Swift 6 refuses an explicit selector like that on a class that conforms to URLSessionTaskDelegate (the compiler sees it clashing with the protocol requirement). That’s true, and also beside the point, since the class above only adopts URLSessionDelegate, compiles fine with swiftc -swift-version 6, and URLSession still calls followRedirect on every redirect.
The other way in is to let Swift infer the selector. A method named URLSession (capital letters) with the redirect labels gets URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler: as soon as Objective-C can see it, and the types don’t matter at all, since types never go into a selector:
@objcMembers final class MembersRedirectHandler: NSObject, URLSessionDelegate {
func URLSession(
_: NSObject,
task: NSObject,
willPerformHTTPRedirection _: NSObject,
newRequest _: NSObject,
completionHandler: @escaping (NSURLRequest?) -> Void
) {
completionHandler(nil)
}
}
What exposes it doesn’t have to sit next to it, either. @objcMembers on a superclass, or on the class an extension extends, can live in another file, so the rule reports a URLSession-named method with those labels without looking for @objc at all.
The rule has to match the Objective-C selector.
Testing against a real redirect
To see which shapes URLSession really calls, we can put each one through the same check. Compile it with swiftc, ask the instance responds(to:) for the selector and list its methods with class_copyMethodList, then point a URLSession with that delegate at a local server that answers 302. A control delegate with no handler follows the redirect and ends up with a 200; a delegate whose handler calls completionHandler(nil) stops it, and the response stays a 302. We care about the status code more than responds(to:), because a method can be in the runtime and still never be asked.
let selector = NSSelectorFromString(
"URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:"
)
print(RenamedRedirectHandler().responds(to: selector)) // true
On Swift 6 these all stopped the redirect: the explicit @objc(...) selector in both the completion-handler and the async form, an @objc protocol requirement carrying the selector (every witness inherits it), the attribute inside an #if, @objc func URLSession in sync, async and async throws forms, and the @objcMembers class, its extension and its subclass. These didn’t, and the rule leaves them alone: a lowercase urlSession: selector, a named first label, the four-label form without async, and a URLSession method nothing exposes to Objective-C (the rule still reports that one, since the exposure can be added from another file).
Two more ways past it
The same harness then turned up two more, and the first is a backticked attribute name:
@`objc`(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func followRedirect(/* ... */)
The compiler treats @`objc` as the built-in attribute, but SwiftParser only recognizes objc from the plain keyword, so it parses the backticked one as a custom attribute with an argument list and most of the selector pieces in unexpected nodes. A rule that waits for the parsed Objective-C name never sees a selector there. The fix was to stop trusting the parse and rebuild the selector from the raw tokens between the attribute’s parentheses, a colon as : and everything else by its canonical name, which reads both parses the same way (and a backticked piece like `URLSession` along with them).
The second is an initializer:
final class InitializerRedirectHandler: NSObject, URLSessionDelegate {
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
init(
_: URLSession,
_: URLSessionTask,
_: HTTPURLResponse,
_: URLRequest,
_ completionHandler: @escaping (URLRequest?) -> Void
) {
completionHandler(nil)
super.init()
}
}
To Objective-C an init is just an instance method, so this one shows up in class_copyMethodList under the redirect selector, and URLSession calls the initializer on the delegate that already exists, in the middle of a redirect. Designated and convenience initializers both work, and an @objc protocol can carry it as an init requirement. The rule only visited function declarations, so it needed to visit initializers too. Subscripts and accessors can’t carry that selector, the compiler rejects it, so they stay out.
Shapes that look right but aren’t the handler
Matching by name and labels also reports a couple of methods that never get the call. A URLSession method with all five labels that is also async gets the selector ...newRequest:completionHandler:completionHandler:, because Swift appends a completion handler for the async part, and a throws one gets an error: piece before the trailing completion handler. Neither is the redirect handler, and the live 302 agreed (200, never called), so the five-label form now has to be neither async nor throws, while the four-label form keeps allowing async throws, which does still map to the redirect selector.
A syntax rule only sees declarations, though. class_addMethod with imp_implementationWithBlock, resolveInstanceMethod(_:) or forwardingTarget(for:) can hand URLSession a redirect handler that no Swift declaration shows, so those need a different kind of check, one that looks for the runtime APIs themselves.
A rule guarding a delegate method an Objective-C class looks up has to match the selector the runtime builds, not the Swift name you’d write. And the way to find out which shapes count is to put each one through a real redirect and check the status code, rather than trusting what the method is called or what responds(to:) says. The shape I first left out, and both of the ones that turned up later, were found that way.