Search code examples
swiftnsurlsessionsubclassingnsurlsessionconfiguration

Initializer does not override a designated initializer while subclassing NSURLSession Swift


I want to subclass NSURLSession class, but I have problem with initialisation. Basically I override the constructor and initialising the constant authUrl there then calling the parent init method.

class NSURLAuthSession: NSURLSession {
    let authUrl:NSURL;

    //Error: Initializer does not override a designated initializer from its superclass
    override init(configuration: NSURLSessionConfiguration, delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?){
        self.authUrl = NSURL.URLWithBaseURLString("http://192.168.10.105:8888/api/v1", pathSegments: ["users", "login"])!
        super.init(configuration: configuration, delegate: delegate, delegateQueue: queue)
    }
}

From the source code of NSURLSession I found out that it has two initializers:

public /*not inherited*/ init(configuration: NSURLSessionConfiguration)
public /*not inherited*/ init(configuration: NSURLSessionConfiguration, delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?)

I expected the "longest" init to be the designated initializer but it's not. I suspect that that designated initializer is the init() that is not even specified in the source code. How can I override the initializer and set up the configuration NSURLSessionConfiguration?


Solution

  • You can not.

    The only designated initializer is NSURLSession.init() and you must call it from your subclass initializer. NSURLSession configuration, delegate and delegateQueue properties are read-only so you can not manually set them.

    The better way is to wrap NSURLSession with custom class:

    class NSURLAuthSession {
        private let urlSession: NSURLSession
    
        init(urlSession: NSURLSession) {
            self.urlSession = urlSession
        }
    }
    

    thus you will have more control and customization options.