iOS开发技巧JS 与 iOS『技术栈』iOS

iOS中的 NSURLProtocol

2015-08-28  本文已影响10951人  JamesYu

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

NSURLProtocol

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

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];
}

注意点:

文章中的示例代码点这里进行下载JYNSURLPRotocolDemo

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

上一篇 下一篇

猜你喜欢

热点阅读