一拦盹、基本使用
引入頭文件#import <WebKit/WebKit.h>
-?(void)setupWebview{
????WKWebViewConfiguration?*config?=?[[WKWebViewConfiguration?alloc]?init];
????config.selectionGranularity?=?WKSelectionGranularityDynamic;
????config.allowsInlineMediaPlayback?=?YES;
????WKPreferences?*preferences?=?[WKPreferences?new];
????//是否支持JavaScript
????preferences.javaScriptEnabled?=?YES;
????//不通過用戶交互痘番,是否可以打開窗口
????preferences.javaScriptCanOpenWindowsAutomatically?=?YES;
????config.preferences?=?preferences;
????WKWebView?*webview?=?[[WKWebView?alloc]?initWithFrame:CGRectMake(0,?0,?KScreenWidth,?KScreenHeight?-?64)?configuration:config];
????[self.view?addSubview:webview];
????/*?加載服務(wù)器url的方法*/
????NSString?*url?=?@"https://www.baidu.com";
????NSURLRequest?*request?=?[NSURLRequest?requestWithURL:[NSURL?URLWithString:url]];
????[webview?loadRequest:request];
????webview.navigationDelegate?=?self;
????webview.UIDelegate?=?self;
}
遵循的協(xié)議和實(shí)現(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ā)送請(qǐng)求之前次酌,決定是否跳轉(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);
}
下面介紹幾個(gè)開發(fā)中需要實(shí)現(xiàn)的小細(xì)節(jié):
1、url中文處理
有時(shí)候我們加載的URL中可能會(huì)出現(xiàn)中文,需要我們手動(dòng)進(jìn)行轉(zhuǎn)碼赚瘦,但是同時(shí)又要保證URL中的特殊字符保持不變,那么我們就可以使用下面的方法(方法放到了NSString中的分類中):
-?(NSURL?*)url{
#pragma?clang?diagnostic?push
#pragma?clang?diagnostic?ignored"-Wdeprecated-declarations"
????return?[NSURL?URLWithString:(NSString?*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,?(CFStringRef)self,?(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",?NULL,kCFStringEncodingUTF8))];
#pragma?clang?diagnostic?pop
}
2奏寨、獲取h5中的標(biāo)題 3起意、添加進(jìn)度條
獲取h5中的標(biāo)題和添加進(jìn)度條放到一起展示看起來更明朗一點(diǎn),在初始化wenview時(shí)病瞳,添加兩個(gè)觀察者分別用來監(jiān)聽webview 的estimatedProgress和title屬性:
webview.navigationDelegate?=?self;
webview.UIDelegate?=?self;
[webview?addObserver:self?forKeyPath:@"estimatedProgress"?options:NSKeyValueObservingOptionNew?context:nil];
[webview?addObserver:self?forKeyPath:@"title"?options:NSKeyValueObservingOptionNew?context:NULL];
添加創(chuàng)建進(jìn)度條杜恰,并添加進(jìn)度條圖層屬性:
@property?(nonatomic,weak)?CALayer?*progressLayer;
-(void)setupProgress{
????UIView?*progress?=?[[UIView?alloc]init];
????progress.frame?=?CGRectMake(0,?0,?KScreenWidth,?3);
????progress.backgroundColor?=?[UIColor??clearColor];
????[self.view?addSubview:progress];
????CALayer?*layer?=?[CALayer?layer];
????layer.frame?=?CGRectMake(0,?0,?0,?3);
????layer.backgroundColor?=?[UIColor?greenColor].CGColor;
????[progress.layer?addSublayer:layer];
????self.progressLayer?=?layer;
}
實(shí)現(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);
????????????});
????????}
????}else?if?([keyPath?isEqualToString:@"title"]){
????????self.title?=?change[@"new"];
????}
}
二、原生JS交互
(一)JS調(diào)用原生方法
在WKWebView中實(shí)現(xiàn)與JS的交互還需要實(shí)現(xiàn)另外一個(gè)代理方法:WKScriptMessageHandler
#pragma?mark?-?WKScriptMessageHandler
-?(void)userContentController:(WKUserContentController?*)userContentController
??????didReceiveScriptMessage:(WKScriptMessage?*)message
在 message的name和body屬性中我們可以獲取到與JS調(diào)取原生的方法名和所傳遞的參數(shù)仍源。
二)原生調(diào)用JS方法
[webview?evaluateJavaScript:“JS語句”?completionHandler:^(id?_Nullable?data,?NSError?*?_Nullable?error)?{
?}];
下面舉例說明:
首先心褐,遵循代理:
<WKScriptMessageHandler>
注冊(cè)方法名:
config.preferences?=?preferences;
WKUserContentController?*user?=?[[WKUserContentController?alloc]init];
[user?addScriptMessageHandler:self?name:@"takePicturesByNative"];
config.userContentController?=user;
實(shí)現(xiàn)代理方法:
#pragma?mark?-?WKScriptMessageHandler
-?(void)userContentController:(WKUserContentController?*)userContentController
??????didReceiveScriptMessage:(WKScriptMessage?*)message{
????if?([message.name?isEqualToString:@"takePicturesByNative"])?{
???????[self?takePicturesByNative];
????}
}
-?(void)takePicturesByNative{
????UIImagePickerController?*vc?=?[[UIImagePickerController?alloc]?init];
????vc.delegate?=?self;
????vc.sourceType?=?UIImagePickerControllerSourceTypePhotoLibrary;
????[self?presentViewController:vc?animated:YES?completion:nil];
}
-?(void)imagePickerController:(UIImagePickerController?*)picker?didFinishPickingMediaWithInfo:(NSDictionary?*)info?{
????NSTimeInterval?timeInterval?=?[[NSDate?date]timeIntervalSince1970];
????NSString?*timeString?=?[NSString?stringWithFormat:@"%.0f",timeInterval];
????UIImage?*image?=?[info??objectForKey:UIImagePickerControllerOriginalImage];
????NSArray?*paths?=?NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,?YES);
????NSString?*filePath?=?[[paths?objectAtIndex:0]?stringByAppendingPathComponent:[NSString?stringWithFormat:@"%@.png",timeString]];??//保存到本地
????[UIImagePNGRepresentation(image)?writeToFile:filePath?atomically:YES];
????NSString?*str?=?[NSString?stringWithFormat:@"%@",filePath];
????[picker?dismissViewControllerAnimated:YES?completion:^{
????????//?oc?調(diào)用js?并且傳遞圖片路徑參數(shù)
????????[self.webview?evaluateJavaScript:[NSString?stringWithFormat:@"getImg('%@')",str]?completionHandler:^(id?_Nullable?data,?NSError?*?_Nullable?error)?{
????????}];
????}];
}
我們期望的效果是,點(diǎn)擊webview中打開相冊(cè)的按鈕笼踩,調(diào)用原生方法逗爹,展示相冊(cè),選擇圖片嚎于,可以傳遞給JS掘而,并展示在webview中。
但是運(yùn)行程序發(fā)現(xiàn):我們可以打開相冊(cè)于购,說明JS調(diào)用原生方法成功了袍睡,但是并不能在webview中展示出來,說明原生調(diào)用JS方法時(shí)肋僧,出現(xiàn)了問題斑胜。這是因?yàn)椋赪KWebView中嫌吠,H5在加載本地的資源(包括圖片止潘、CSS文件、JS文件等等)時(shí)辫诅,默認(rèn)被禁止了凭戴,所以根據(jù)我們傳遞給H5的圖片路徑,無法展示圖片炕矮。解決辦法:在傳遞給H5的圖片路徑中添加我們自己的請(qǐng)求頭么夫,攔截H5加載資源的請(qǐng)求頭進(jìn)行判斷者冤,拿到路徑然后由我們來手動(dòng)請(qǐng)求。
先為圖片路徑添加一個(gè)我們自己的請(qǐng)求頭:
NSString?*str?=?[NSString?stringWithFormat:@"myapp://%@",filePath];
然后創(chuàng)建一個(gè)新類繼承于NSURLProtocol
.h
#import?
@interface?MyCustomURLProtocol?:?NSURLProtocol
@end
.m
@implementation?MyCustomURLProtocol
+?(BOOL)canInitWithRequest:(NSURLRequest*)theRequest{
????if?([theRequest.URL.scheme?caseInsensitiveCompare:@"myapp"]?==?NSOrderedSame)?{
????????return?YES;
????}
????return?NO;
}
+?(NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest{
????return?theRequest;
}
-?(void)startLoading{
????NSURLResponse?*response?=?[[NSURLResponse?alloc]?initWithURL:[self.request?URL]
????????????????????????????????????????????????????????MIMEType:@"image/png"
???????????????????????????????????????????expectedContentLength:-1
????????????????????????????????????????????????textEncodingName:nil];
????NSString?*imagePath?=?[self.request.URL.absoluteString?componentsSeparatedByString:@"myapp://"].lastObject;
????NSData?*data?=?[NSData?dataWithContentsOfFile:imagePath];
????[[self?client]?URLProtocol:self?didReceiveResponse:response?cacheStoragePolicy:NSURLCacheStorageNotAllowed];
????[[self?client]?URLProtocol:self?didLoadData:data];
????[[self?client]?URLProtocolDidFinishLoading:self];
}
-?(void)stopLoading{
}
@end
在控制器中注冊(cè)MyCustomURLProtocol協(xié)議并添加對(duì)myapp協(xié)議的監(jiān)聽:
?//注冊(cè)
????[NSURLProtocol?registerClass:[MyCustomURLProtocol?class]];
????//實(shí)現(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
????}