在Swift 2中继承AFHTTPSessionManager的正确方法

时间:2016-01-06 15:30:13

标签: objective-c swift afnetworking

我已经在objective-c中编写了AFHTTPSessionManager并将其子类化了,因此这就是它的样子:

+ (APIClient *)sharedAPIClient
{
    static APIClient *_sharedAPIClient = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedAPIClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:BaseURL]];
    });

    return _sharedAPIClient;
}

- (instancetype)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];

    if (self) {
        self.responseSerializer = [AFJSONResponseSerializer serializer];
        self.requestSerializer = [AFJSONRequestSerializer serializer];
    }

    return self;
}

我可以通过以下方式获得此课程的实例:

var objAPIClient = APIClient()
objAPIClient = APIClient.sharedAPIClient()

我已经查看了堆栈溢出的以下资源:

AFHTTPSessionManager subclass swift

Swift - Why init(coder) is required in AFHTTPSessionManager?

通过实施以下代码:

let _sharedAPIManager = APIManager(baseURL: NSURL(string: API_URL)!)

class APIManager: AFHTTPSessionManager {

    /**
     * Singleton service 
     * (https://github.com/hpique/SwiftSingleton)
     */
    class var sharedInstance : APIManager {
        return _sharedAPIManager
    }

    init(baseURL url: NSURL!) {
        super.init(baseURL: url, sessionConfiguration: nil)

        self.responseSerializer = AFJSONResponseSerializer() as AFJSONResponseSerializer
        self.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer

        self.requestSerializer.setValue(API_KEY, forHTTPHeaderField: "X-Api-Key")
        self.requestSerializer.setValue("3", forHTTPHeaderField: "X-Api-Version")
    }

    // this was inserted by XCode
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

它是否返回一个实际的单例,因为init应该是私有的?我如何制作此代码的实例? var x = APIManager.sharedInstance

将_sharedAPIManager放在课堂之外是不对的?这个代码是否完全像我的objective-c版本,在我的objective-c实现中它只运行一个?

1 个答案:

答案 0 :(得分:2)

您可以在_sharedAPIManager内移动APIManager并将其重命名为sharedInstance。然后,您可以将初始化程序声明为私有:

class APIManager: AFHTTPSessionManager {
    static let sharedInstance = APIManager(baseURL: NSURL(string: API_URL)!)

    private init(baseURL url: NSURL!) {

您可以通过APIManager.sharedInstance访问单例实例。