WKWebView在實際開發(fā)中的使用匯總

一、基本使用

引入頭文件#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];


????/*?加載服務器url的方法*/

????NSString?*url?=?@"https://www.baidu.com";

????NSURLRequest?*request?=?[NSURLRequest?requestWithURL:[NSURL?URLWithString:url]];

????[webview?loadRequest:request];


????webview.navigationDelegate?=?self;

????webview.UIDelegate?=?self;

}

遵循的協(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);

}

/*?在收到響應后,決定是否跳轉(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?[NSURL?URLWithString:(NSString?*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,?(CFStringRef)self,?(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",?NULL,kCFStringEncodingUTF8))];

#pragma?clang?diagnostic?pop

}

2、獲取h5中的標題 3、添加進度條

獲取h5中的標題和添加進度條放到一起展示看起來更明朗一點,在初始化wenview時,添加兩個觀察者分別用來監(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)建進度條,并添加進度條圖層屬性:

@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;

}

實現(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中實現(xiàn)與JS的交互還需要實現(xiàn)另外一個代理方法: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>

注冊方法名:

config.preferences?=?preferences;

WKUserContentController?*user?=?[[WKUserContentController?alloc]init];

[user?addScriptMessageHandler:self?name:@"takePicturesByNative"];

config.userContentController?=user;

實現(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)?{

????????}];

????}];

}

我們期望的效果是,點擊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?=?[NSString?stringWithFormat:@"myapp://%@",filePath];

然后創(chuàng)建一個新類繼承于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

在控制器中注冊MyCustomURLProtocol協(xié)議并添加對myapp協(xié)議的監(jiān)聽:

?//注冊

????[NSURLProtocol?registerClass:[MyCustomURLProtocol?class]];

????//實現(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

????}

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容