1.H5加载页面缓慢,考虑使用离线化加载。 确保[低速网络]或[无网络]可网页秒开。
2.使用[NSURLProtocol]拦截 区别于uiwebview wkwebview使用如下方法拦截
[NSURLProtocol registerClass:[MyCustomProtocol class]];
Class cls = NSClassFromString(@"WKBrowsingContextController");
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if ([(id)cls respondsToSelector:sel]) {
[(id)cls performSelector:sel withObject:@"http"];
[(id)cls performSelector:sel withObject:@"https"];
}
MyCustomProtocol.h
#import <Foundation/Foundation.h>
@interface MyCustomProtocol : NSURLProtocol
@end
MyCustomProtocol.m
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest {
if ([theRequest.URL.absoluteString containsString:@"https://www.baidu.com/img/login_2d2c57b59121dec81f374c4fe080e9d3.png"]) {
return YES;
}
return NO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest *)theRequest {
return theRequest;
}
- (void)startLoading {
NSMutableURLRequest* request = self.request.mutableCopy;
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
MIMEType:@"image/png"
expectedContentLength:-1
textEncodingName:nil];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
NSLog(@"start loading !");
}
- (void)stopLoading {
NSLog(@"something went wrong!");
}
3、使用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[NSURLProtocol registerClass:[MyCustomProtocol class]];
Class cls = NSClassFromString(@"WKBrowsingContextController");
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if ([(id)cls respondsToSelector:sel]) {
[(id)cls performSelector:sel withObject:@"http"];
[(id)cls performSelector:sel withObject:@"https"];
}
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
[self.view addSubview:self.webView];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
}