AFHTTPSessionManager子类swift [英] AFHTTPSessionManager subclass swift

查看:218
本文介绍了AFHTTPSessionManager子类swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }

}

同时尝试将此代码用作 self.sessionManager = HTTPManager.sharedInstance 它总是崩溃并显示消息

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


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

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

但MyApp.DefaultSessionConfiguration是NSURLSessionConfiguration的子类,因此毫无保留地拥有此属性

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

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

So, how do we solve this problem?

推荐答案

问题在于您不应该直接实例化 NSURLSessionConfiguration 。您应该通过调用以下类方法之一来实例化它: defaultSessionConfiguration ephemeralSessionConfiguration backgroundSessionConfigurationWithIdentifier 。例如:

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

这篇关于AFHTTPSessionManager子类swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆