iOS中的 NSURLProtocol

作者: JamesYu | 来源:发表于2015-08-28 12:52 被阅读10951次

最近做SDK开发的时候,为了给QA编写一个测试工具,方便调试和记录请求内容。但是又不想改动已经写好的SDK代码。本来想到用methodSwizzle,但是发现SDK要开放一些私有的类出来,太麻烦,也不方便最后的打包。于是网上搜了下,如何黑魔法下系统的回调函数,无意中发现了NSURLProtocol这个牛逼玩意。。。所有问题都被它给解决了。。。。

NSURLProtocol

NSURLProtocol是 iOS里面的URL Loading System的一部分,但是从它的名字来看,你绝对不会想到它会是一个对象,可是它偏偏是个对象。。。而且还是抽象对象(可是OC里面没有抽象这一说)。平常我们做网络相关的东西基本很少碰它,但是它的功能却强大得要死。

  • 可以拦截UIWebView,基于系统的NSUIConnection或者NSUISession进行封装的网络请求。
  • 忽略网络请求,直接返回自定义的Response
  • 修改request(请求地址,认证信息等等)
  • 返回数据拦截
  • 干你想干的。。。

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

nsobject_hierarchy_2x.png

# 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这个协议的对象将消息转给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;

你会发现和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

上面都是基于NSURLConnection的例子,iOS7之后的NSURLSession是一样遵循的,不过里面需要改成NSURLSession相关的东西。可用看看官方的例子CustomHTTPProtocol

相关文章

  • iOS中的 NSURLProtocol 初识

    iOS中的 NSURLProtocol 简介 NSURLProtocol是 iOS 里面的URL Loading ...

  • NSURLProtocol

    NSURLProtocol NSURLProtocol 是 iOS里面的URL Loading System的一部...

  • iOS端网络拦截技术

    iOS端网络拦截技术 NSURLProtocol NSURLProtocol是URL Loading System...

  • iOS中的NSURLProtocol

    转自:iOS知识小集 NSURLProtocol类(注意,这个不是协议)经常用于实现一些URL Loading S...

  • iOS中的 NSURLProtocol

    最近做SDK开发的时候,为了给QA编写一个测试工具,方便调试和记录请求内容。但是又不想改动已经写好的SDK代码。本...

  • 【iOS开发】NSURLProtocol的使用

    参考文章:iOS开发之--- NSURLProtocolNSURLProtocol NSURLProtocol 是...

  • NSURLProtocol

    iOS开发之--- NSURLProtocolNSURLProtocol-重镜像NSURLProtocol-缓存

  • iOS NSURLProtocol

    前言:NSURLProtocol是NSURLConnection的handle类, 它更像一套协议,如果遵守这套协...

  • [iOS] NSURLProtocol

    前言:最近在了解HttpDns的实现方案,经过调研,发现了NSURLProtocol这个在Apple URL Lo...

  • iOS中NSURLProtocol 的简单研究

    之前在做完HTTPDNS服务以后, 为了使用IP代替域名, 使用的方式是改造网络库, 也就是直接在网络库层改造NS...

网友评论

  • A777727:您好,POST请求丢失body怎么搞?
  • 上发条的树:你好,请问有时候一些H5页面的替换本地图片显示不出来,遇到过这种情况吗?
  • eb410aa21d76:你好,有个问题遇到了,在使用这个做webview的缓存的时候,特别问下哈

    start loading 里面的这个,就是走了缓存了
    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]; }

    完了,如果我后台去请求下载这个URL,完了,更新缓存,完了 怎么样 更新 当前页面呢? 因为当前页面用的是 一进来从缓存拿到的数,后来我又在后台更新了缓存,有可能 缓存不一样了,所以我要顺便也更新下 当前页面,如果调用
    [self.client URLProtocol:self didReceiveResponse
    [self.client URLProtocol:self didLoadData
    [self.client URLProtocolDidFinishLoading
    这三个代理方法,我看了是不管用的,也就是说webview当前页面,并没有二次更新下页面(最最新的缓存)

    - (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]; }
  • Jvaeyhcd:您好,请问

    //采用 SDWebImage 的转换方法
    UIImage *imgData = [UIImage sd_imageWithWebPData:data];返回为空?为什么呢?
  • ReinhardHuang:最近查资料总能查到静静的简书,俨然已成为大神级人物,膜拜下
    ReinhardHuang:@JamesYu 同程 XX旻
    JamesYu:你是谁啊。
  • 千秋画雪:特别详细
  • Misaki_yuyi:求楼主帮助啊
    我这边的需求是把网页的一部分 css 和js文件放到本地,然后请求的时候,遇到特定的资源文件不去请求,替换成本地的文件 。我只有在+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
    {
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];

    if ([mutableReqeust.URL.absoluteString hasSuffix:@"angular.js"])
    {
    NSString * filePath = [[NSBundle mainBundle]pathForResource:@"angular" ofType:@"js"];
    NSURL * fileurl = [NSURL fileURLWithPath:filePath];
    mutableReqeust = [NSMutableURLRequest requestWithURL:fileurl];
    }

    return mutableReqeust;
    }

    替换完了之后,项目就报错 WebThread的错,不知道错在什么地方了。求楼主解答
  • 8a567a6ebd2e:查资料查着查着就发现一个特熟悉的名字,然后我就知道,早就该多跟庾大师多学习的,要不何苦沦落到现在才研究到~哎~
    JamesYu:@刘三太子 是你这货啊。。。
  • c80d1c560c1e:你好,NSURLProtocol这个例子,加载http://t.sina.com.cn时为什么页面是乱的呢?
    Alanxx:@Misaki_yuyi 前辈 我现在也遇到这样的问题,请问你当时是怎么解决的呢?能留个联系方式吗
    Misaki_yuyi:@yangtclive 我不知道层主有没有遇到这样的问题。请求网页,里面部分的js和css资源文件需要放在本地,不去请求。所以在+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request方法里面 加入了下面的代码 但是报错了

    NSMutableURLRequest *mutableReqeust = [request mutableCopy];

    if ([mutableReqeust.URL.absoluteString hasSuffix:@"angular.js"])
    {
    NSString * filePath = [[NSBundle mainBundle]pathForResource:@"angular" ofType:@"js"];
    NSURL * fileurl = [NSURL fileURLWithPath:filePath];
    mutableReqeust = [NSMutableURLRequest requestWithURL:fileurl];
    }

    return mutableReqeust;

    不知道报错的原因是什么求解答 :pray:
    JamesYu:@yangtclive 是页面排版还是啥?

本文标题:iOS中的 NSURLProtocol

本文链接:https://www.haomeiwen.com/subject/nchkcttx.html