NSURLProtocol

2019-07-24  本文已影响0人  酱油瓶2

NSURLProtocol

NSURLProtocol 是 iOS里面的URL Loading System的一部分,URL loading system 原生已经支持了 http,https,file,ftp,data 这些常见协议,当然也允许我们定义自己的 protocol 去扩展,或者定义自己的协议。当URL loading system通过 NSURLRequest 对象进行请求时,将会自动创建 NSURLProtocol (是一个对象)的实例(可以是自定义的),这样我们就有机会对该请求进行处理。

URL Loading System不清楚的,可以看看下面这张图,看看里面有哪些类:

image.png



使用NSURLProtocol的主要可以分为5个步骤:
注册—>拦截—>转发—>回调—>结束

NSURLProtocol的创建

@interface CFTHTTPProtocol : NSURLProtocol

@end
[NSURLProtocol registerClass:[CFTHTTPProtocol class]];

子类NSURLProtocol必须实现的方法

+ (BOOL)canInitWithRequest:(NSURLRequest *)request;
+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b;
- (void)startLoading;
- (void)stopLoading;

实现NSURLSessionDataDelegate和NSURLSessionTaskDelegate

回调,如果你对你关注的请求进行了拦截,那么你就需要通过实现 NSURLProtocolClient 这个协议的对象将消息转给URL loading system,也就是 NSURLProtocol 中的 client 这个对象。看看这个 NSURLProtocolClient 里面的方法:

- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;

- (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse;

- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy;

- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;

- (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol;

- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

- (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

你会发现和 NSURLSessionDelegate 很像,其实就是做了个转发的操作。

上一篇 下一篇

猜你喜欢

热点阅读