Search code examples
swiftfoundationurlsession

Does assigning a custom URLSessionDelegate override default behavior for methods that are not implemented?


In the documentation for URLSessionDelegate it says:

Your URLSession object doesn’t need to have a delegate. If no delegate is assigned, a system-provided delegate is used, and you must provide a completion callback to obtain the data.

I only need to implement one of the methods like this:

class SessionDelegate: NSObject, URLSessionTaskDelegate {
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        var request = request
        request.httpMethod = task.originalRequest?.httpMethod ?? request.httpMethod
        completionHandler(request)
    }
}

And then initialize my session like this:

self.session = URLSession(configuration: config, delegate: SessionDelegate(), delegateQueue: nil)

Does that override any other behavior in the "system-provided delegate" for the methods that I didn't implement?


Solution

  • Any (optional) functions you don't override in your SessionDelegate class will respect the default implementation behaviour of the original functions.

    In order to check the default behaviour for each function, please see the documentation in the header files (option+click on URLSessionTaskDelegate) or here:

    https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate