AFHTTPSessionManager subclass swift

痞子三分冷 提交于 2019-12-11 12:26:05

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/33853319/afhttpsessionmanager-subclass-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!