学习 Swift Moya(一)

What is Moya ?

So the basic idea of Moya is that we want some network abstraction layer that sufficiently encapsulates actually calling Alamofire directly. It should be simple enough that common things are easy, but comprehensive enough that complicated things are also easy.

Link: https://github.com/Moya/Moya

Feature

Some awesome features of Moya:

  • Compile-time checking for correct API endpoint accesses.
  • Lets you define a clear usage of different endpoints with associated enum values.
  • Treats test stubs as first-class citizens so unit testing is super-easy.

Components

学习 Swift Moya(一)_第1张图片
2016-06-28_Moya.png

Default Configure

  • MoyaProvider Default init
public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
    requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
    stubClosure: StubClosure = MoyaProvider.NeverStub,
    manager: Manager = MoyaProvider.DefaultAlamofireManager(),
    plugins: [PluginType] = []) {
        
        self.endpointClosure = endpointClosure
        self.requestClosure = requestClosure
        self.stubClosure = stubClosure
        self.manager = manager
        self.plugins = plugins
}
  • Default EndpointClosure
public final class func DefaultEndpointMapping(target: Target) -> Endpoint {
    let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
    return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
  • Default RequestMapping
public final class func DefaultRequestMapping(endpoint: Endpoint, closure: NSURLRequest -> Void) {
    return closure(endpoint.urlRequest)
}
  • Default Manager
public final class func DefaultAlamofireManager() -> Manager {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders

    let manager = Manager(configuration: configuration)
    manager.startRequestsImmediately = false
    return manager
}

Reference: Moya Docs

你可能感兴趣的:(学习 Swift Moya(一))