美文网首页
学习 Swift Moya(一)

学习 Swift Moya(一)

作者: jkyeo | 来源:发表于2016-06-30 15:32 被阅读767次

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

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<Target>.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<Target> {
    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<Target>, 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(一)

      本文链接:https://www.haomeiwen.com/subject/ejffjttx.html