公司新项目里面,主要是以原生作为框架,详情页面有web页面负责展示。iOS这边是用WKWebView来加载web页面,但是由于网络环境和页面复杂度的问题,iOS 端和安卓 的web加载速度很慢。(客户服务器域名的问题)
1、把所有web的资源包放到本地:问题依旧在
2、web页面共有的资源包放到原生本地,web页面加载时,先判断本地是否有资源包,优先加载本地资源包。
参考:https://segmentfault.com/a/1190000005732602
https://blog.csdn.net/u011154007/article/details/68068172
https://blog.csdn.net/hanhailong18/article/details/79394856
核心原理:
对H5请求进行拦截,如果本地已经有对应的静态资源文件,则直接加载,这样就能达到“秒开”webview的效果。
对于iOS而言,这就需要用到NSURLProtocol这个神器了。接下来,分析下它到底是什么东西,我们怎么利用它达到上述效果。
NSURLProtocol:它能够让你去重新定义苹果的URL加载系统(URL Loading System)的行为,URL Loading System里有许多类用于处理URL请求,比如NSURL,NSURLRequest,NSURLConnection和NSURLSession等。当URL Loading System使用NSURLRequest去获取资源的时候,它会创建一个NSURLProtocol子类的实例,你不应该直接实例化一个NSURLProtocol,NSURLProtocol看起来像是一个协议,但其实这是一个 类,而且必须使用该类的子类,并且需要被注册。
换句话说,NSURLProtocol能拦截所有当前app下的网络请求,并且能自定义地进行处理。
直接上代码
#import "NSURLProtocolCustom.h"
#import <CoreFoundation/CoreFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
static NSString* const FilteredKey = @"FilteredKey";
@interface NSURLProtocolCustom()<NSURLConnectionDataDelegate>
@property(nonatomic, strong)NSURLConnection *coonection;
@end
@implementation NSURLProtocolCustom
//这个方法的作用是判断当前protocol是否要对这个request进行处理(所有的网络请求都会走到这里,所以我们只需要对我们产生的request进行处理即可)。
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
NSString *extension = request.URL.pathExtension;
BOOL isSource = [@[@"png", @"jpeg", @"gif", @"jpg", @"js", @"css"] indexOfObjectPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
return [extension compare:obj options:NSCaseInsensitiveSearch] == NSOrderedSame;
}] != NSNotFound;
return [NSURLProtocol propertyForKey:FilteredKey inRequest:request] == nil && isSource;
}
//可以对request进行预处理,比如对header加一些东西什么的,我们这里没什么要改的,所以直接返回request就好了。
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
return request;
}
//我们这里需要做一件事,就是自己拼装httpResponse,并且返回给url load system,然后到了webview那一层,会收到response,对于webview而言,加载本地和走网络拿到的response是完全一样的。所以上述代码展示了如何拼装一个httpResponse,当组装完成后,需要调用self.client将数据传出去。
- (void)startLoading
{
//fileName 获取web页面加载的资源包文件名(js css等)
NSString *fileName = [super.request.URL.absoluteString componentsSeparatedByString:@"/"].lastObject;
//这里是获取本地资源路径 如:png,js等
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
NSLog(@"fileName is %@ path=%@",fileName,path);
if (!path) {
//本地资源包没有所需的文件,加载网络请求
NSMutableURLRequest *newrequest = [self.request mutableCopy];
newrequest.allHTTPHeaderFields = self.request.allHTTPHeaderFields;
[NSURLProtocol setProperty:@YES forKey:FilteredKey inRequest:newrequest];
self.coonection = [NSURLConnection connectionWithRequest:newrequest delegate:self];
return;
}
//根据路径获取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];
}
- (void)stopLoading
{
[self.coonection cancel];
NSLog(@"stopLoading, something went wrong!");
}
- (void)sendResponseWithData:(NSData *)data mimeType:(nullable NSString *)mimeType
{
NSMutableDictionary *header = [[NSMutableDictionary alloc]initWithCapacity:2];
NSString *contentType = [mimeType stringByAppendingString:@";charset=UTF-8"];
header[@"Content-Type"] = contentType;
header[@"Content-Length"] = [NSString stringWithFormat:@"%lu",(unsigned long) data.length];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc]initWithURL:self.request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:header];
// 这里需要用到MIMEType
//NSURLResponse *response = [[NSURLResponse alloc] initWithURL:super.request.URL MIMEType:mimeType expectedContentLength:-1 textEncodingName:nil];
//硬编码 开始嵌入本地资源到web中
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}
#pragma 代理
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.client URLProtocol:self didLoadData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.client URLProtocolDidFinishLoading:self];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.client URLProtocol:self didFailWithError:error];
}
@end
目前,关于拦截并加载本地资源包的代码操作就没有了,剩下还有一步,就是在加载web页面之前,对自定义的NSURLProtocol 进行注册,使上面的代码实现对资源的拦截
-(void)setNSURLProtocolCustom{
//注册
[NSURLProtocol registerClass:[NSURLProtocolCustom class]];
//实现拦截功能,这个是核心
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
}
}
结语:之前单纯加载web页面的时候,加载时间基本都是在两秒以上,现在基本控制在两秒以内了 。
网友评论