最近公司的項目中大量使用了webview加載H5,鑒于WKWebView的性能優(yōu)于UIWebView,所以就選擇了WKWebView。WKWebView在使用的過程中,還是有很過內(nèi)容值得我們?nèi)ビ涗浐脱芯康模@里我就做了一下總結(jié),跟大家分享一下。文章中的示例代碼可以到github中下載查看。
一、基本使用
WKWebView的基本使用網(wǎng)上也有很多,這里我就簡略的寫一下:
引入頭文件#import
- (void)setupWebview{
WKWebViewConfiguration*config = [[WKWebViewConfigurationalloc] init];
config.selectionGranularity =WKSelectionGranularityDynamic;
config.allowsInlineMediaPlayback =YES;
WKPreferences*preferences = [WKPreferencesnew];
//是否支持JavaScript
preferences.javaScriptEnabled =YES;
//不通過用戶交互,是否可以打開窗口
preferences.javaScriptCanOpenWindowsAutomatically =YES;
config.preferences = preferences;
WKWebView*webview = [[WKWebViewalloc] initWithFrame:CGRectMake(0,0, KScreenWidth, KScreenHeight -64) configuration:config];
[self.view addSubview:webview];
/* 加載服務(wù)器url的方法*/
NSString*url =@"https://www.baidu.com";
NSURLRequest*request = [NSURLRequestrequestWithURL:[NSURLURLWithString:url]];
[webview loadRequest:request];
webview.navigationDelegate =self;
webview.UIDelegate =self;
}
WKWebViewConfiguration和WKPreferences中有很多屬性可以對webview初始化進行設(shè)置,這里就不一一介紹了。
遵循的協(xié)議和實現(xiàn)的協(xié)議方法:
#pragma mark - WKNavigationDelegate
/* 頁面開始加載 */
- (void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation{
}
/* 開始返回內(nèi)容 */
- (void)webView:(WKWebView*)webView didCommitNavigation:(WKNavigation*)navigation{
}
/* 頁面加載完成 */
- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation{
}
/* 頁面加載失敗 */
- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation{
}
/* 在發(fā)送請求之前,決定是否跳轉(zhuǎn) */
- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler{
//允許跳轉(zhuǎn)
decisionHandler(WKNavigationActionPolicyAllow);
//不允許跳轉(zhuǎn)
//decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到響應(yīng)后,決定是否跳轉(zhuǎn) */
- (void)webView:(WKWebView*)webView decidePolicyForNavigationResponse:(WKNavigationResponse*)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler{
NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//允許跳轉(zhuǎn)
decisionHandler(WKNavigationResponsePolicyAllow);
//不允許跳轉(zhuǎn)
//decisionHandler(WKNavigationResponsePolicyCancel);
}
下面介紹幾個開發(fā)中需要實現(xiàn)的小細節(jié):
1、url中文處理
有時候我們加載的URL中可能會出現(xiàn)中文,需要我們手動進行轉(zhuǎn)碼,但是同時又要保證URL中的特殊字符保持不變,那么我們就可以使用下面的方法(方法放到了NSString中的分類中):
- (NSURL*)url{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
return[NSURLURLWithString:(NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8))];
#pragma clang diagnostic pop
}
2、獲取h5中的標(biāo)題 3、添加進度條
獲取h5中的標(biāo)題和添加進度條放到一起展示看起來更明朗一點,在初始化wenview時,添加兩個觀察者分別用來監(jiān)聽webview 的estimatedProgress和title屬性:
webview.navigationDelegate =self;
webview.UIDelegate =self;
[webview addObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNewcontext:nil];
[webview addObserver:selfforKeyPath:@"title"options:NSKeyValueObservingOptionNewcontext:NULL];
添加創(chuàng)建進度條,并添加進度條圖層屬性:
@property(nonatomic,weak)CALayer*progressLayer;
-(void)setupProgress{
UIView*progress = [[UIViewalloc]init];
progress.frame =CGRectMake(0,0, KScreenWidth,3);
progress.backgroundColor = [UIColorclearColor];
[self.view addSubview:progress];
CALayer*layer = [CALayerlayer];
layer.frame =CGRectMake(0,0,0,3);
layer.backgroundColor = [UIColorgreenColor].CGColor;
[progress.layer addSublayer:layer];
self.progressLayer = layer;
}
實現(xiàn)觀察者的回調(diào)方法:
#pragma mark - KVO回饋
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context{
if([keyPath isEqualToString:@"estimatedProgress"]) {
self.progressLayer.opacity =1;
if([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
return;
}
self.progressLayer.frame =CGRectMake(0,0, KScreenWidth*[change[@"new"] floatValue],3);
if([change[@"new"]floatValue] ==1.0) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progressLayer.opacity =0;
self.progressLayer.frame =CGRectMake(0,0,0,3);
});
}
}elseif([keyPath isEqualToString:@"title"]){
self.title = change[@"new"];
}
}
下面是實現(xiàn)的效果圖:
3、添加userAgent信息
有時候H5的伙伴需要我們?yōu)閣ebview的請求添加userAgent,以用來識別操作系統(tǒng)等信息,但是如果每次用到webview都要添加一次的話會比較麻煩,下面介紹一個一勞永逸的方法。
在Appdelegate中添加一個WKWebview的屬性,啟動app時直接,為該屬性添加userAgent:
- (void)setUserAgent {
_webView = [[WKWebViewalloc] initWithFrame:CGRectZero];
[_webView evaluateJavaScript:@"navigator.userAgent"completionHandler:^(idresult,NSError*error) {
if(error) {return; }
NSString*userAgent = result;
if(![userAgent containsString:@"/mobile-iOS"]) {
userAgent = [userAgent stringByAppendingString:@"/mobile-iOS"];
NSDictionary*dict = @{@"UserAgent": userAgent};
[TKUserDefaults registerDefaults:dict];
}
}];
}
這樣一來,在app中創(chuàng)建的webview都會存在我們添加的userAgent的信息。
二、原生JS交互
(一)JS調(diào)用原生方法
在WKWebView中實現(xiàn)與JS的交互還需要實現(xiàn)另外一個代理方法:WKScriptMessageHandler
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message
在 message的name和body屬性中我們可以獲取到與JS調(diào)取原生的方法名和所傳遞的參數(shù)。
打印一下如下圖所示:
JS調(diào)用原生方法的代碼:
window.webkit.messageHandlers.takePicturesByNative.postMessage({
"picType":"0",
"picCount":"9",
"callBackName":"getImg"
})
}
注意:JS只能向原生傳遞一個參數(shù),所以如果有多個參數(shù)需要傳遞,可以讓JS傳遞對象或者JSON字符串即可。
(二)原生調(diào)用JS方法
[webview evaluateJavaScript:“JS語句” completionHandler:^(id _Nullable data, NSError * _Nullable error) {
}]
;
下面舉例說明:
實現(xiàn)H5通過原生方法調(diào)用相冊
首先,遵循代理:
注冊方法名:
config.preferences = preferences;
WKUserContentController*user = [[WKUserContentControlleralloc]init];
[user addScriptMessageHandler:selfname:@"takePicturesByNative"];
config.userContentController =user;
實現(xiàn)代理方法:
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message{
if([message.name isEqualToString:@"takePicturesByNative"]) {
[selftakePicturesByNative];
}
}
- (void)takePicturesByNative{
UIImagePickerController*vc = [[UIImagePickerControlleralloc] init];
vc.delegate =self;
vc.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
[selfpresentViewController:vc animated:YEScompletion:nil];
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSTimeIntervaltimeInterval = [[NSDatedate]timeIntervalSince1970];
NSString*timeString = [NSStringstringWithFormat:@"%.0f",timeInterval];
UIImage*image = [info ?objectForKey:UIImagePickerControllerOriginalImage];
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSStringstringWithFormat:@"%@.png",timeString]];//保存到本地
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
NSString*str = [NSStringstringWithFormat:@"%@",filePath];
[picker dismissViewControllerAnimated:YEScompletion:^{
// oc 調(diào)用js 并且傳遞圖片路徑參數(shù)
[self.webview evaluateJavaScript:[NSStringstringWithFormat:@"getImg('%@')",str] completionHandler:^(id_Nullable data,NSError* _Nullable error) {
}];
}];
}
我們期望的效果是,點擊webview中打開相冊的按鈕,調(diào)用原生方法,展示相冊,選擇圖片,可以傳遞給JS,并展示在webview中。
但是運行程序發(fā)現(xiàn):我們可以打開相冊,說明JS調(diào)用原生方法成功了,但是并不能在webview中展示出來,說明原生調(diào)用JS方法時,出現(xiàn)了問題。這是因為,在WKWebView中,H5在加載本地的資源(包括圖片、CSS文件、JS文件等等)時,默認被禁止了,所以根據(jù)我們傳遞給H5的圖片路徑,無法展示圖片。解決辦法:在傳遞給H5的圖片路徑中添加我們自己的請求頭,攔截H5加載資源的請求頭進行判斷,拿到路徑然后由我們來手動請求。
先為圖片路徑添加一個我們自己的請求頭:
NSString*str = [NSStringstringWithFormat:@"myapp://%@",filePath];
然后創(chuàng)建一個新類繼承于NSURLProtocol
.h
#import
@interfaceMyCustomURLProtocol:NSURLProtocol
@end
.m
@implementationMyCustomURLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest{
if([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] ==NSOrderedSame) {
returnYES;
}
returnNO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest{
returntheRequest;
}
- (void)startLoading{
NSURLResponse*response = [[NSURLResponsealloc] initWithURL:[self.request URL]
MIMEType:@"image/png"
expectedContentLength:-1
textEncodingName:nil];
NSString*imagePath = [self.request.URL.absoluteString componentsSeparatedByString:@"myapp://"].lastObject;
NSData*data = [NSDatadataWithContentsOfFile:imagePath];
[[selfclient] URLProtocol:selfdidReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[selfclient] URLProtocol:selfdidLoadData:data];
[[selfclient] URLProtocolDidFinishLoading:self];
}
- (void)stopLoading{
}
@end
在控制器中注冊MyCustomURLProtocol協(xié)議并添加對myapp協(xié)議的監(jiān)聽:
//注冊
[NSURLProtocolregisterClass:[MyCustomURLProtocolclass]];
//實現(xiàn)攔截功能
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:@"myapp"];
#pragma clang diagnostic pop
}
運行程序,效果如下:
不僅僅是加載本地的圖片,webview加載任何本地的資源都可以使用該方法,不過在使用過程中,大家一定要密切注意跨域問題會帶來的安全性問題。
結(jié)尾
關(guān)于WKWebView其實還有很多內(nèi)容,接下來我還會繼續(xù)深入地去探究WKWebView的原理和使用。
作者:沐澤sunshine
鏈接:http://www.lxweimin.com/p/5dab90e2e5f1