网络层的福尔摩斯:ResponseDetective
fefre
9年前
ResponseDetective 是一个非侵入式框架用于拦截任何传出请求和输入响应在你的App和你的服务器之间,以达到调试的目的。
Usage
Incorporating ResponseDetective in your project is very simple – it all comes down to a couple of steps.
Step 1: Register interceptors
You may register as many request, response and error interceptors as you like.
// request InterceptingProtocol.registerRequestInterceptor(BaseInterceptor()) InterceptingProtocol.registerRequestInterceptor(JSONInterceptor()) // response InterceptingProtocol.registerResponseInterceptor(BaseInterceptor()) InterceptingProtocol.registerResponseInterceptor(JSONInterceptor()) InterceptingProtocol.registerResponseInterceptor(HTMLInterceptor()) // error InterceptingProtocol.registerErrorInterceptor(BaseInterceptor())
Step 2: Register the protocol
ForInterceptingProtocolto work, it needs to be added as a middleman between yourNSURLSessionand the Internet. You can do this by registering it in your session'sNSURLSessionConfiguration.protocolClasses.let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.protocolClasses = [InterceptingProtocol.self] let session = NSURLSession(configuration: configuration)
If you're using Alamofire as your networking framework, integrating ResponseDetective is as easy as initializing yourManagerwithNSURLSessionConfigurationdescribed above.
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.protocolClasses = [InterceptingProtocol.self] let manager = Alamofire.Manager(configuration: configuration)
Step 3: Profit
Now it's time to perform the actual request.
let request = NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")!) let task = session.dataTaskWithRequest(request) task.resume()
Voilà! Now check out your console output.
200 no error Content-Length: 301 Server: nginx Content-Type: application/json Access-Control-Allow-Origin: * Date: Wed, 08 Jul 2015 13:10:13 GMT Access-Control-Allow-Credentials: true Connection: keep-alive { "args" : { }, "headers" : { "User-Agent" : "ResponseDetective\/1 CFNetwork\/711.4.6 Darwin\/15.0.0", "Accept-Encoding" : "gzip, deflate", "Host" : "httpbin.org", "Accept-Language" : "en-us", "Accept" : "*\/*" }, "origin" : "109.206.223.85", "url" : "http:\/\/httpbin.org\/get" }