今天要整理的是:NSURLProtocol
NSURLProtocol是 URL Loading System的一部分翘地,它是一個(gè)抽象類(lèi),想要使用子類(lèi)繼承并實(shí)現(xiàn)癌幕、然后注冊(cè)衙耕。
它能干嘛?
攔截基于系統(tǒng)的NSUIConnection或者NSUISession進(jìn)行封裝的網(wǎng)絡(luò)請(qǐng)求(如使用WKWebView勺远、UIWebView)
單單一個(gè)攔截橙喘,這里就可以實(shí)現(xiàn)很多你想要實(shí)現(xiàn)的功能,例如:
- 解決dns域名劫持(白名單或黑名單)
- 加載本地緩存胶逢、本地js渴杆、css、image等靜態(tài)資源
- 修改request宪塔,重定向
實(shí)現(xiàn)
首先實(shí)現(xiàn)是繼承的NSURLProtocol的子類(lèi)
#import <Foundation/Foundation.h>
@interface NSURLProtocolCustom : NSURLProtocol
@end
然后在合適的地方進(jìn)行注冊(cè)
[NSURLProtocol registerClass:[CustomURLProtocol class]];
一經(jīng)注冊(cè)之后磁奖,所有交給URL Loading system的網(wǎng)絡(luò)請(qǐng)求都會(huì)被攔截,所以當(dāng)不需要攔截的時(shí)候某筐,要進(jìn)行注銷(xiāo)
[NSURLProtocol unregisterClass:[NSURLProtocolCustom class]];
在CustomURLProtocol里必須要實(shí)現(xiàn)的方法:
canInitWithRequest 簡(jiǎn)單的說(shuō)是請(qǐng)求的入口比搭,所有的請(qǐng)求都會(huì)先進(jìn)入到這里,如果希望攔截下來(lái)自己處理南誊,那么就返回YES身诺,否則就返回NO。
需要注意的地方是抄囚,當(dāng)自己去處理這個(gè)請(qǐng)求的時(shí)候霉赡,由于URL Loading System會(huì)創(chuàng)建一個(gè)CustomURLProtocol實(shí)例后通過(guò)NSURLConnection去獲取數(shù)據(jù),NSURLConnection又會(huì)調(diào)用URL Loading System幔托,這樣會(huì)造成死循環(huán)穴亏,解決的方法是通過(guò)setProperty:forKey:inRequest:標(biāo)記那些已經(jīng)處理過(guò)的request蜂挪,如果是已經(jīng)處理的就返回NO。
通常canonicalRequestForRequest方法你可以直接返回request嗓化,但也可以在這里做修改棠涮,比如添加header,修改host等
當(dāng)需要自己處理該請(qǐng)求的時(shí)候刺覆,startLoading便會(huì)被調(diào)起严肪,在這里你可以處理自己的邏輯。
加載本地js谦屑、css資源驳糯,緩存h5圖片
在實(shí)際項(xiàng)目運(yùn)行中,很多時(shí)候我們需要加載h5氢橙,但由于h5里有很多基礎(chǔ)的js與css结窘,這些基礎(chǔ)資源基本不會(huì)有變化或者有些資源過(guò)大,網(wǎng)絡(luò)不穩(wěn)定的情況下會(huì)出現(xiàn)加載中斷充蓝,所以在做webview優(yōu)化的時(shí)候,我們可以抽離出這部分的資源文件喉磁,打包到項(xiàng)目里來(lái)谓苟,然后使用NSURLProtocol來(lái)進(jìn)行加載,以減少這部分文件的網(wǎng)絡(luò)請(qǐng)求协怒。同樣的涝焙,h5里的圖片資源也可以通過(guò)NSURLProtocol加上SDWebImage進(jìn)行加載并且緩存。
代碼:
#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"]) {
//基礎(chǔ)靜態(tài)資源孕暇,h5上已經(jīng)做了統(tǒng)一路徑處理仑撞,可以以此:://resource 前序來(lái)判斷是否需要攔截
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來(lái)加載圖片,間接實(shí)現(xiàn)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];
//標(biāo)記該請(qǐng)求已經(jīng)處理
[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) {
//根據(jù)路徑獲取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
最后
- 對(duì)于WKWebView妖滔,想要使用NSURLProtocol的話(huà)隧哮,注冊(cè)的時(shí)候記得加上以下代碼
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
}
- 靜態(tài)資源如果想要更新,可以單獨(dú)開(kāi)接口去下載座舍,保存到沙箱中沮翔,同時(shí)將讀取文件的方式由bundle改為沙箱。
demo
以上便是NSURLProtocol一些介紹曲秉,上面提到的加載本地資源文件demo MYLCustom也已經(jīng)放到github采蚀,有興趣的可以下載研究兼打個(gè)call。