Skip to content

Latest commit

 

History

History
52 lines (37 loc) · 1.83 KB

CustomizingNetworkingBackend.md

File metadata and controls

52 lines (37 loc) · 1.83 KB

Customizing Networking Backend

APIKit uses NSURLSession as networking backend by default. Since Session has abstraction layer of backend called SessionAdapterType, you can change the backend of Session like below:

Demo implementation of Alamofire adapter is available here.

SessionAdapterType

SessionAdapterType provides an interface to get (NSData?, NSURLResponse?, NSError?) from NSURLRequest and returns SessionTaskType for cancellation.

public protocol SessionAdapterType {
    func resumedTaskWithURLRequest(URLRequest: NSURLRequest, handler: (NSData?, NSURLResponse?, NSError?) -> Void) -> SessionTaskType
    func getTasksWithHandler(handler: [SessionTaskType] -> Void)
}

public protocol SessionTaskType: class {
    func cancel()
}

How Session works with SessionAdapterType

Session takes an instance of type that conforms SessionAdapterType as a parameter of initializer.

public class Session {
    public let adapter: SessionAdapterType

    public init(adapter: SessionAdapterType) {
        self.adapter = adapter
    }

    ...
}

Once it is initialized with a session adapter, it sends NSURLRequest and receives (NSData?, NSURLResponse?, NSError?) via the interfaces which are defined in SessionAdapterType.

func sendRequest<T: RequestType>(request: T, handler: (Result<T.Response, APIError>) -> Void = {r in}) -> SessionTaskType? {
    let URLRequest: NSURLRequest = ...
    let task = adapter.resumedTaskWithURLRequest(URLRequest) { data, URLResponse, error in
        ...
    }
}