IOS理论知识iOS学习开发iOS点点滴滴

iOS UIWebView小整理(三)(利用NSURLProto

2017-12-15  本文已影响562人  MyLee

今天要整理的是:NSURLProtocol

NSURLProtocol是 URL Loading System的一部分,它是一个抽象类,想要使用子类继承并实现、然后注册。

URLLoadingSystem.png

它能干嘛?

拦截基于系统的NSUIConnection或者NSUISession进行封装的网络请求(如使用WKWebView、UIWebView)

单单一个拦截,这里就可以实现很多你想要实现的功能,例如:

实现

首先实现是继承的NSURLProtocol的子类

#import <Foundation/Foundation.h>
@interface NSURLProtocolCustom : NSURLProtocol
@end

然后在合适的地方进行注册

[NSURLProtocol registerClass:[CustomURLProtocol class]];

一经注册之后,所有交给URL Loading system的网络请求都会被拦截,所以当不需要拦截的时候,要进行注销

[NSURLProtocol unregisterClass:[NSURLProtocolCustom class]];

在CustomURLProtocol里必须要实现的方法:

canInitWithRequest.png

canInitWithRequest 简单的说是请求的入口,所有的请求都会先进入到这里,如果希望拦截下来自己处理,那么就返回YES,否则就返回NO。
需要注意的地方是,当自己去处理这个请求的时候,由于URL Loading System会创建一个CustomURLProtocol实例后通过NSURLConnection去获取数据,NSURLConnection又会调用URL Loading System,这样会造成死循环,解决的方法是通过setProperty:forKey:inRequest:标记那些已经处理过的request,如果是已经处理的就返回NO。


canonicalRequestForRequest.png

通常canonicalRequestForRequest方法你可以直接返回request,但也可以在这里做修改,比如添加header,修改host等

loading.png

当需要自己处理该请求的时候,startLoading便会被调起,在这里你可以处理自己的逻辑。

加载本地js、css资源,缓存h5图片

在实际项目运行中,很多时候我们需要加载h5,但由于h5里有很多基础的js与css,这些基础资源基本不会有变化或者有些资源过大,网络不稳定的情况下会出现加载中断,所以在做webview优化的时候,我们可以抽离出这部分的资源文件,打包到项目里来,然后使用NSURLProtocol来进行加载,以减少这部分文件的网络请求。同样的,h5里的图片资源也可以通过NSURLProtocol加上SDWebImage进行加载并且缓存。

代码:

#import "NSURLProtocolCustom.h"
#import "NSString+PJR.h"
#import "UIImageView+WebCache.h"
#import "NSData+ImageContentType.h"
#import "UIImage+MultiFormat.h"

static NSString* const FilteredKey = @"FilteredKey";

@interface NSURLProtocolCustom ()

@property (nonatomic, strong) NSMutableData *responseData;
@property (nonatomic, strong) NSURLConnection *connection;
@end

@implementation NSURLProtocolCustom

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSURL *url = request.URL;
    NSString *scheme = [url scheme];
    
    if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
          [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame))
    {
        NSString *requestUrl = url.absoluteString;
        
        NSLog(@"HTTPMethod:%@",request.HTTPMethod);
        NSLog(@"Protocol URL:%@",requestUrl);
        
        NSString *extension = url.pathExtension;
        
        if ([requestUrl containsString:@"://resource"]) {
            //基础静态资源,h5上已经做了统一路径处理,可以以此:://resource 前序来判断是否需要拦截
            if ([extension isEqualToString:@"js"] || [extension isEqualToString:@"css"]) {
                NSString *fileName = [[request.URL.absoluteString componentsSeparatedByString:@"/"].lastObject componentsSeparatedByString:@"?"][0];
                NSLog(@"fileName is %@",fileName);
                //从bundle中读取
                NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
                //从沙箱读取
      //        NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
      //        NSString *path = [docPath stringByAppendingPathComponent:fileName];
                if (path) {
                    NSLog(@"the file is local file");
                    return [NSURLProtocol propertyForKey:FilteredKey inRequest:request] == nil;
                }
            }
        }
        
        if ([extension isPicResource]) {
            //用sdwebimage来加载图片,间接实现h5图片缓存功能
            return [NSURLProtocol propertyForKey:FilteredKey inRequest:request]== nil;
        }
        
    }
    
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}

- (void)startLoading
{
    NSURL *url = super.request.URL;
    NSString *requestUrl = url.absoluteString;
    NSString *extension = url.pathExtension;
    
    NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
    //标记该请求已经处理
    [NSURLProtocol setProperty:@YES forKey:FilteredKey inRequest:mutableReqeust];
    
    if ([requestUrl containsString:@"://resource"]) {
        //获取本地资源路径
        NSString *fileName = [[requestUrl componentsSeparatedByString:@"/"].lastObject componentsSeparatedByString:@"?"][0];
        //从bundle中读取
        NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
        //从沙箱读取
//        NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//        NSString *path = [docPath stringByAppendingPathComponent:fileName];
        if (path) {
            //根据路径获取MIMEType
            CFStringRef pathExtension = (__bridge_retained CFStringRef)[path pathExtension];
            CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
            CFRelease(pathExtension);
            
            //The UTI can be converted to a mime type:
            NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType);
            if (type != NULL)
                CFRelease(type);
            
            //加载本地资源
            NSData *data = [NSData dataWithContentsOfFile:path];
            [self sendResponseWithData:data mimeType:mimeType];
            
            return;
        }else{
            NSLog(@"%@ is not find",fileName);
        }
    }else if([extension isPicResource]){
        //处理图片缓存
        NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
        UIImage *img = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
        
        if (img) {
            //存在图片缓存
            NSData *data = nil;
            if ([extension isEqualToString:@"png"]) {
                data = UIImagePNGRepresentation(img);
            }else{
                data = UIImageJPEGRepresentation(img, 1);
            }
            NSString *mimeType = [NSData sd_contentTypeForImageData:data];
            [self sendResponseWithData:data mimeType:mimeType];
            
            return ;
        }
        
        self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];
    }
}

- (void)stopLoading
{
    NSLog(@"stopLoading from networld");
    if (self.connection) {
        [self.connection cancel];
    }
}

- (void)sendResponseWithData:(NSData *)data mimeType:(nullable NSString *)mimeType
{
    NSLog(@"sendResponseWithData start");
    // 这里需要用到MIMEType
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:super.request.URL
                                                        MIMEType:mimeType
                                           expectedContentLength:data.length
                                                textEncodingName:nil];
    
    if ([self client]) {
        if ([self.client respondsToSelector:@selector(URLProtocol:didReceiveResponse:cacheStoragePolicy:)]) {
            [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        }
        if ([self.client respondsToSelector:@selector(URLProtocol:didLoadData:)]) {
            [[self client] URLProtocol:self didLoadData:data];
        }
        if ([self.client respondsToSelector:@selector(URLProtocolDidFinishLoading:)]) {
            [[self client] URLProtocolDidFinishLoading:self];
        }
    }
    
    NSLog(@"sendResponseWithData end");
}

#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];
    NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
    
    [[SDImageCache sharedImageCache] storeImage:cacheImage
                           recalculateFromImage:NO
                                      imageData:self.responseData
                                         forKey:key
                                         toDisk:YES];
    
    [self.client URLProtocolDidFinishLoading:self];
}

@end

最后

Class cls = NSClassFromString(@"WKBrowsingContextController");
        SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
        if ([(id)cls respondsToSelector:sel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [(id)cls performSelector:sel withObject:@"http"];
            [(id)cls performSelector:sel withObject:@"https"];
#pragma clang diagnostic pop
        }

demo

以上便是NSURLProtocol一些介绍,上面提到的加载本地资源文件demo MYLCustom也已经放到github,有兴趣的可以下载研究兼打个call。

个人站点记录

上一篇下一篇

猜你喜欢

热点阅读