konex 0.5.1

konex 0.5.1

测试已测试
Lang语言 SwiftSwift
许可证 MIT
Released上次发布2017年2月
SwiftSwift 版本3.0
SPM支持 SPM

Fernando Ortiz 维护。



konex 0.5.1

  • fmo91

konex

简介

Konex 是一个用 Swift 编写的轻量级面向协议的网络库,可以轻松扩展或修改。它通过强制每个请求在单独的对象中实现来强制实施网络层组织。Konex 可选择将响应解析为 JSON 对象。

简例

Konex 库的核心是 KonexRequest 协议。所以,您首先要做的是在一个结构体或类中实现这个协议。

struct GetAllPostsRequest: KonexRequest {
    let path = "https://jsonplaceholder.typicode.com/posts/"
    let method = .post
}

我们需要一个可以像这样写的 Post 类

import ObjectMapper

struct Post: KonexJSONDecodable {
    var id: Int?
    var title = ""

    init() {}

    static func instantiate(withJSON json: [String : Any]) -> Post? {
        var post = Post()

        post.id = json["id"] as? Int
        post.title = json["title"] as? String

        return post
    }
}

对我们的目的来说,Post 类实现 KonexJSONDecodable 协议是很重要的。一旦有了模型和请求模型,我们就可以调度请求并获取响应了。

负责调度请求的类是 KonexClient。它可以直接使用,因此您可以在任何需要的地方实例化并开始使用它。

let client = KonexClient()

let request = GetAllPostsRequest()

client.requestArray(of: Post.self,
    request: request,
    onSuccess: { (posts: [Post]) in
        // You can do whatever you want with your posts!
    },
    onError: { (error: Error) in
        // You should handle this...
    }
)

这就全部了!如果您喜欢面向对象编程,可以拥有基本请求。本节以下将扩展更多。

创建请求

您可以通过面向协议或面向对象的方式建模您的请求。

面向协议的请求:Konex 提供了 KonexRequest 协议,您的请求必须实现才能由 KonexClient 分发。KonexRequest 是 Konex 库中非常重要的一部分。一个 KonexRequest 定义了以下可以在您的请求中实现的属性:

  • path:表示请求 URL 的字符串。这是唯一的必需属性
  • method:表示请求 HTTP 方法的枚举值。它是 Konex.HTTPMethod 类型。默认为 .get
  • parameters:一个 JSON 对象,在 .get 请求的情况下将添加到请求 URL 中,或者在任何其他情况下将添加到 HTTP 主体中。默认为 nil
  • headers:请求头。默认为 nil

此外, 还允许您添加 Konex 扩展组件,这些组件仅适用于您的请求。将在本指南的后续部分中解释 Konex 扩展组件,但在此阶段,它们是这样的:

  • requestPlugins:它是 KonexPlugin 对象的数组。默认为 []。
  • requestResponseProcessors:它是一个KonexResponseProcessor对象的数组。默认为[]。
  • requestResponseValidators:它是一个KonexResponseValidator对象的数组。默认为[]。

面向对象请求:除了基于协议的方式,Konex还允许您用更面向对象的方式来建模您的请求。Konex定义了实现KonexRequest协议并可被完全继承的KonexBasicRequest类。不能直接使用。它有点像抽象类。必须继承

open class KonexBasicRequest: KonexRequest {
    open var requestPlugins: [KonexPlugin] { return [] }
    open var requestResponseProcessors: [KonexResponseProcessor] { return [] } 
    open var requestResponseValidators: [KonexResponseValidator] { return [] }

    open var path: String { return "" }
    open var method: Konex.HTTPMethod { return .get }
    open var parameters: [String : Any]? { return [:] }
    open var headers: [String : String]? { return [:] }

    public init() {}
}

很简单。您可以继承它并定义自己的基础请求或类似的东西。您也可以有一个认证请求或类似的东西。您可以自由地创建自己的请求层次结构。

请求分发

要分发KonexRequest对象,您需要一个KonexClientKonexClient依赖于URLSession来分发请求。因此,第一步是创建一个KonexClient。这可以通过其初始化器完成

let client = KonexClient()

这将其URLSession属性成员初始化为URLSession.default。如果您愿意,可以使用此初始化器注入另一个URLSession

let client = KonexClient(urlSession: anotherSession)

一旦您拥有一个KonexClient,您就可以使用它来分发KonexRequest对象。

KonexClient定义了三种方法来完成此操作

open func request(
    request: KonexRequest, 
    plugins localPlugins: [KonexPlugin] = [], 
    responseProcessors localResponseProcessors: [KonexResponseProcessor] = [], 
    responseValidators localResponseValidators: [KonexResponseValidator] = [], 
    onSuccess: @escaping (Any) -> Void, 
    onError: @escaping (Error) -> Void) -> URLSessionDataTask?

request方法定义了执行请求的核心逻辑。它分发您的请求,并向其传递两个闭包,一个用于成功情况,另一个用于错误情况。

KonexClient还可以解析响应,您可以获取数据的最终版本。有两种方法:requestObjectrequestArray,它们都是相似的。

open func requestObject<T:Mappable>(ofType type: T.Type, 
    request: KonexRequest, 
    plugins localPlugins: [KonexPlugin] = [], 
    responseProcessors localResponseProcessors: [KonexResponseProcessor] = [],
    responseValidators localResponseValidators: [KonexResponseValidator] = [],
    onSuccess: @escaping (T) -> Void, 
    onError: @escaping (Error) -> Void) -> URLSessionDataTask?

open func requestArray<T: Mappable>(of type: T.Type, 
    request: KonexRequest, 
    plugins localPlugins: [KonexPlugin] = [], 
    responseProcessors localResponseProcessors: [KonexResponseProcessor] = [],
    responseValidators localResponseValidators: [KonexResponseValidator] = [], 
    onSuccess: @escaping ([T]) -> Void, 
    onError: @escaping (Error) -> Void) -> URLSessionDataTask?

最后,KonexClient是一个开放类,因此它的成员方法,您可以按自己的意愿定制它。

拓展Konex

Konex定义了三个协议,您可以使用它们来扩展您的请求分发逻辑。

  • KonexPlugin:定义了两个方法:didSendRequestdidReceiveResponse。这可以是一个网络日志记录器或网络指示处理器的一个例子。
  • KonexResponseProcessor:定义了func process(response: Any) -> Any,允许您创建功能管道来处理在分发请求之后到来的响应。
  • KonexResponseValidator:定义了func validate(response: Any) throws

Konex组件可以在三个不同的级别添加

  • 客户端级别KonexClient公开了名为pluginsresponseProcessorsresponseValidators的属性,您可以在这里附加您的扩展组件。
  • 请求级别KonexRequest定义了三个属性:requestPluginsrequestResponseProcessorsrequestResponseValidators
  • 方法级别KonexClient的方法接受其参数内的扩展组件。

示例

要运行示例项目,首先克隆存储库,然后从Example目录运行pod install

要求

安装

Konex可以通过CocoaPods获得。要安装它,只需将以下行添加到您的Podfile中

pod "Konex"

作者

fmo91,[email protected]

许可

Konex 可以在MIT许可证下使用。有关更多信息,请参阅LICENSE文件。