AFHTTPSessionManager子类swift

时间:2015-11-22 09:25:34

标签: ios swift afnetworking-2 afhttpsessionmanager

使用自定义会话配置创建AFHTTPSessionManager的单一子类的正确方法是什么?

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

    }

}

尝试将此代码用作self.sessionManager = HTTPManager.sharedInstance时,它始终与消息

一起崩溃
  

[MyApp.DefaultSessionConfiguration setHTTPShouldSetCookies:]:   无法识别的选择器发送到实例0x7f99f8f31b70

但是MyApp.DefaultSessionConfiguration是NSURLSessionConfiguration的子类,而且还有这种方法。

那么,我们如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

问题是你不应该直接实例化NSURLSessionConfiguration。您应该通过调用以下类方法之一来实例化它:defaultSessionConfigurationephemeralSessionConfigurationbackgroundSessionConfigurationWithIdentifier。例如:

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