测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布上一次发布 | 2017年3月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 JPAlary 维护。
这个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。