iOS中的NSURLProtocol
来源:互联网 发布:c语言入门小程序 编辑:程序博客网 时间:2024/05/17 05:13
最近做SDK开发的时候,为了给QA编写一个测试工具,方便调试和记录请求内容。但是又不想改动已经写好的SDK代码。本来想到用methodSwizzle,但是发现SDK要开放一些私有的类出来,太麻烦,也不方便最后的打包。于是网上搜了下,如何黑魔法下系统的回调函数,无意中发现了NSURLProtocol这个牛逼玩意。。。所有问题都被它给解决了。。。。
NSURLProtocol
NSURLProtocol
是 iOS里面的URL Loading System的一部分,但是从它的名字来看,你绝对不会想到它会是一个对象,可是它偏偏是个对象。。。而且还是抽象对象
(可是OC里面没有抽象这一说)。平常我们做网络相关的东西基本很少碰它,但是它的功能却强大得要死。
- 可以拦截UIWebView,基于系统的NSUIConnection或者NSUISession进行封装的网络请求。
- 忽略网络请求,直接返回自定义的Response
- 修改request(请求地址,认证信息等等)
- 返回数据拦截
- 干你想干的。。。
对URL Loading System不清楚的,可以看看下面这张图,看看里面有哪些类:
# iOS中的 NSURLProtocol
URL loading system
原生已经支持了http
,https
,file
,ftp
,data
这些常见协议,当然也允许我们定义自己的protocol
去扩展,或者定义自己的协议。当URL loading system
通过NSURLRequest
对象进行请求时,将会自动创建NSURLProtocol
的实例(可以是自定义的)。这样我们就有机会对该请求进行处理。官方文档里面介绍得比较少,下面我们直接看如何自定义NSURLProtocol
,并结合两个简单的demo看下如何使用。
NSURLProtocol的创建
首先是继承系统的NSURLProtocol
:
@interface CustomURLProtocol : NSURLProtocol@end
在AppDelegate
里面进行注册下:
[NSURLProtocol registerClass:[CustomURLProtocol class]];
这样,我们就完成了协议的注册。
子类NSURLProtocol必须实现的方法
+ (BOOL)canInitWithRequest:(NSURLRequest *)request;
这个方法是自定义protocol
的入口,如果你需要对自己关注的请求进行处理则返回YES
,这样,URL loading system
将会把本次请求的操作都给了你这个protocol
。
+ (BOOL)canInitWithRequest:(NSURLRequest *)request;
这个方法主要是用来返回格式化好的request
,如果自己没有特殊需求的话,直接返回当前的request
就好了。如果你想做些其他的,比如地址重定向,或者请求头的重新设置,你可以copy
下这个request
然后进行设置。
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b;
这个方法用于判断你的自定义reqeust
是否相同,这里返回默认实现即可。它的主要应用场景是某些直接使用缓存而非再次请求网络的地方。
- (void)startLoading;- (void)stopLoading;
这个两个方法很明显是请求发起和结束的地方。
实现NSURLConnectionDelegate和NSURLConnectionDataDelegate
如果你对你关注的请求进行了拦截,那么你就需要通过实现NSURLProtocolClient
这个协议的对象将消息转给URLloading 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;
你会发现和NSURLConnectionDelegate
很像。其实就是做了个转发的操作。
具体的看下两个demo
最常见的http请求,返回本地数据进行测试
static NSString * const hasInitKey = @"JYCustomDataProtocolKey";@interface JYCustomDataProtocol ()@property (nonatomic, strong) NSMutableData *responseData;@property (nonatomic, strong) NSURLConnection *connection;@end@implementation JYCustomDataProtocol+ (BOOL)canInitWithRequest:(NSURLRequest *)request{ if ([NSURLProtocol propertyForKey:hasInitKey inRequest:request]) { return NO; } return YES;}+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { NSMutableURLRequest *mutableReqeust = [request mutableCopy]; //这边可用干你想干的事情。。更改地址,或者设置里面的请求头。。 return mutableReqeust;}- (void)startLoading{ NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy]; //做下标记,防止递归调用 [NSURLProtocol setProperty:@YES forKey:hasInitKey inRequest:mutableReqeust]; //这边就随便你玩了。。可以直接返回本地的模拟数据,进行测试 BOOL enableDebug = NO; if (enableDebug) { NSString *str = @"测试数据"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; NSURLResponse *response = [[NSURLResponse alloc] initWithURL:mutableReqeust.URL MIMEType:@"text/plain" expectedContentLength:data.length textEncodingName:nil]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; [self.client URLProtocol:self didLoadData:data]; [self.client URLProtocolDidFinishLoading:self]; } else { self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self]; }}- (void)stopLoading{ [self.connection cancel];}#pragma mark- NSURLConnectionDelegate- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self.client URLProtocol:self didFailWithError:error];}#pragma mark - NSURLConnectionDataDelegate- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ self.responseData = [[NSMutableData alloc] init]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.responseData appendData:data]; [self.client URLProtocol:self didLoadData:data];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self.client URLProtocolDidFinishLoading:self];}
UIWebView图片缓存解决方案(结合SDWebImage)
思路很简单,就是拦截请求URL带.png
.jpg
.gif
的请求,首先去缓存里面取,有的话直接返回,没有的去请求,并保存本地。
static NSString * const hasInitKey = @"JYCustomWebViewProtocolKey";@interface JYCustomWebViewProtocol ()@property (nonatomic, strong) NSMutableData *responseData;@property (nonatomic, strong) NSURLConnection *connection;@end@implementation JYCustomWebViewProtocol+ (BOOL)canInitWithRequest:(NSURLRequest *)request{ if ([request.URL.scheme isEqualToString:@"http"]) { NSString *str = request.URL.path; //只处理http请求的图片 if (([str hasSuffix:@".png"] || [str hasSuffix:@".jpg"] || [str hasSuffix:@".gif"]) && ![NSURLProtocol propertyForKey:hasInitKey inRequest:request]) { return YES; } } return NO;}+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { NSMutableURLRequest *mutableReqeust = [request mutableCopy]; //这边可用干你想干的事情。。更改地址,提取里面的请求内容,或者设置里面的请求头。。 return mutableReqeust;}- (void)startLoading{ NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy]; //做下标记,防止递归调用 [NSURLProtocol setProperty:@YES forKey:hasInitKey inRequest:mutableReqeust]; //查看本地是否已经缓存了图片 NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; NSData *data = [[SDImageCache sharedImageCache] diskImageDataBySearchingAllPathsForKey:key]; if (data) { NSURLResponse *response = [[NSURLResponse alloc] initWithURL:mutableReqeust.URL MIMEType:[NSData sd_contentTypeForImageData:data] expectedContentLength:data.length textEncodingName:nil]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; [self.client URLProtocol:self didLoadData:data]; [self.client URLProtocolDidFinishLoading:self]; } else { self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self]; }}- (void)stopLoading{ [self.connection cancel];}#pragma mark- NSURLConnectionDelegate- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self.client URLProtocol:self didFailWithError:error];}#pragma mark - NSURLConnectionDataDelegate- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ self.responseData = [[NSMutableData alloc] init]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.responseData appendData:data]; [self.client URLProtocol:self didLoadData:data];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ UIImage *cacheImage = [UIImage sd_imageWithData:self.responseData]; //利用SDWebImage提供的缓存进行保存图片 [[SDImageCache sharedImageCache] storeImage:cacheImage recalculateFromImage:NO imageData:self.responseData forKey:[[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL] toDisk:YES]; [self.client URLProtocolDidFinishLoading:self];}
注意点:
- 每次只能只有一个
protocol
进行处理,如果有多个自定义protocol
,系统将采取你registerClass
的倒序进行调用,一旦你需要对这个请求进行处理,那么接下来的所有相关操作都需要这个protocol
进行管理。 - 一定要注意标记请求,不然你会无限的循环下去。。。因为一旦你需要处理这个请求,那么系统会创建你这个
protocol
的实例,然后你自己又开启了connection
进行请求的话,又会触发URL Loading system的回调。系统给我们提供了+ (void)setProperty:(id)value forKey:(NSString *)key inRequest:(NSMutableURLRequest *)request;
和+ (id)propertyForKey:(NSString *)key inRequest:(NSURLRequest *)request;
这两个方法进行标记和区分。
文章中的示例代码点这里进行下载JYNSURLPRotocolDemo
- iOS中的NSURLProtocol
- iOS中的NSURLProtocol
- iOS开发之--- NSURLProtocol
- iOS开发之--- NSURLProtocol
- iOS开发之--- NSURLProtocol
- iOS开发之--- NSURLProtocol
- iOS开发之--- NSURLProtocol
- iOS开发之--- NSURLProtocol
- iOS 开发之— NSURLProtocol
- NSURLProtocol
- IOS混合编程 - NSURLProtocol 的使用 (三)
- iOS开发之NSURLProtocol的那些坑
- iOS-NSURLProtocol的理解与应用
- iOS之网页缓存html----NSURLCache-----NSURLProtocol
- IOS网络篇1之截取本地URL请求(NSURLProtocol)
- IOS网络篇2之客户端离线缓存策略(NSURLProtocol)
- iOS平台利用 NSURLProtocol 实现网络数据缓存
- iOS 开发中使用 NSURLProtocol 拦截 HTTP 请求
- iScroll API 整理学习笔记
- TS Intro - PES packet format
- 第十三周文件操作1
- Arrays 类的相关方法使用,数组的拷贝,排序,二分法
- tomcat中日志输出的位置
- iOS中的NSURLProtocol
- 关于嵌入式系统的学习路线图
- Redis源码解析——字典结构
- 我的第一个SDK
- 折腾二维数组
- JavaScript(二)input输入正则表达式
- 置换,循环,模拟(像素混合,LA 3510)
- iOS面试题目
- 数据库事务隔离级别