SwiftInterceptor 2.0

SwiftInterceptor 2.0

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

JPAlary 维护。



  • JPAlary

Swift-interceptor

介绍

这个Interceptor“概念”来自Android库Okhttp(见Okhttp拦截器wiki)中的Interceptor实现。在输入对象的过程前后修改/执行一些操作的时候,这个机制非常强大。拦截器可以视为输入对象源和最终目的地之间的中介。

在这个Swift实现中,还增加了两件事:

  • 泛型输入。
  • 异步处理:拦截器不直接同步返回输出,而是决定过程结束时调用闭包。

使用Interceptor,您有

  • 干净且健壮地处理
    • 网络监视
    • 在单个位置添加所有请求的参数
    • 身份验证(获取/刷新令牌)。在发送请求之前对请求进行签名。
    • 重试失败的请求
    • 更多的功能.. :)

  • 清晰的职责分配
    • 每个拦截器都有一个明确的目的
    • 在输入对象上只执行一件事情

  • 通过每个拦截器上的单元测试轻松提高测试覆盖率

最后,由于其泛型,您可以将此机制应用于其他上下文中。创意无限! :)

使用

拦截器

首先要做的是创建您需要的Interceptor(s)。记住,Interceptor设计用来拦截输入对象。按关注点分组您的Interceptor并避免重复

要做到这一点,您只需遵守Interceptor协议即可

protocol Interceptor {
    associatedtype Input

    func intercept(chain: InterceptorChain<Input>, completion: (Input) -> Void) -> Void
}

示例

拦截输入

struct MyInterceptor: Interceptor {
    func intercept(chain: InterceptorChain<URLRequest>, completion: (URLRequest) -> Void) -> Void {
        // 1) Retrieve the input object (the request)
        var request = chain.input

        // 2) Do things with/on the request

        // 3) Give it back to the chain
        chain.input = request

        // 4) Continue the chaining to others interceptors. /!\ Don't forget to call this, if you don't, you will get stuck in this interceptor.
        chain.proceed(completion: completion)
    }
}

拦截器链


当您实现了自己的拦截器后,就结束!

要启动该过程

// 1) I create an instance of interceptor chain. You can add many interceptor you want.
let chain = InterceptorChain()
    .add(interceptor: AnyInterceptor(base: MyInterceptor()))
chain.input = request

// 2) Launch the process
chain.proceed { (request) in
    // 3) I get my request intercepted by all the interceptors
}

更多信息

关于拦截器机制的更多信息,请参阅okhttp wiki中的文档。对于RxSwift爱好者,还有一个使用RxSwift的相同实现,请参阅SwiftRxInterceptor