Search code examples
iosswiftafnetworking-2afhttpsessionmanager

AFHTTPSessionManager subclass swift


What is the correct way to create singletone subclass of AFHTTPSessionManager with custom session configuration?

class DefaultSessionConfiguration: NSURLSessionConfiguration {

    override init () {

        super.init()

        self.HTTPShouldSetCookies = true
        HTTPCookieStorage?.cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
        HTTPAdditionalHeaders = [ "Content-Type": "application/json"];
    }

}

let baseUrl = "https://google.com"

class HTTPManager: AFHTTPSessionManager {


    static let _sharedAPIManager = HTTPManager(baseURL: NSURL(string: baseUrl)!, sessionConfiguration:DefaultSessionConfiguration())

    class var sharedInstance : HTTPManager {
        return _sharedAPIManager
    }

    override init(baseURL url: NSURL!, sessionConfiguration session:NSURLSessionConfiguration? ) {

        super.init(baseURL: url, sessionConfiguration: session)
        self.responseSerializer = AFJSONResponseSerializer() as AFJSONResponseSerializer
        self.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer

    }

}

While trying to use this code as self.sessionManager = HTTPManager.sharedInstance it is always crashed with message

[MyApp.DefaultSessionConfiguration setHTTPShouldSetCookies:]: unrecognized selector sent to instance 0x7f99f8f31b70

but MyApp.DefaultSessionConfiguration is subclass of NSURLSessionConfiguration and defenetly has this method.

So, how do we solve this problem?


Solution

  • The issue is that you shouldn't be instantiating a NSURLSessionConfiguration directly. You should instantiate it by calling one of the following class methods: defaultSessionConfiguration, ephemeralSessionConfiguration or backgroundSessionConfigurationWithIdentifier. For example:

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPShouldSetCookies = true
    configuration.HTTPCookieStorage?.cookieAcceptPolicy = .Always