使用WKWebView 學(xué)習(xí)記錄:
WKWebView 和 Safari瀏覽器一樣 用的是 Nirtro JavaScript 引擎
可以做一些UIWebView你不能做的事情(我遇到的,我用UIWebView 加載H5 其中H5中 調(diào)用手機的相冊和錄制視頻功能,使用沒有反應(yīng),點擊沒有效果咏瑟,后來換成WKWebView 就可以使用是整,我想和它使用JavaScript引擎有關(guān)系吧)
更多相關(guān)內(nèi)容: http://nshipster.cn/wkwebkit/
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
_webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
[self.view addSubview:_webView];
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
UIBarButtonItem * leftBackItem = [[UIBarButtonItem alloc] initWithTitle:@"Go Back" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClick)];
self.navigationItem.leftBarButtonItem = leftBackItem;
-(void)leftButtonClick{
if ([self.webView canGoBack]) {
[self.webView goBack];
}else{
NSLog(@"***** 當(dāng)前處理棧頂 ****");
}
}
//類似UIWebView的 -webViewDidStartLoad:頁面開始加載時調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"***** 頁面開始加載 *****");
}
// 當(dāng)內(nèi)容開始返回時調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
NSLog(@"***** 服務(wù)器開始返回內(nèi)容 *****");
}
// 頁面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//頁面加載完成 后將navigationBar的標(biāo)題修改成 網(wǎng)頁的標(biāo)題
if(webView.title && webView.title.length > 0) {
self.title= webView.title;
}
}
// 類似 UIWebView 的- webView:didFailLoadWithError:頁面加載失敗時調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"***** 加載網(wǎng)頁失敗,網(wǎng)絡(luò)故障! *****");
}
// 接收到服務(wù)器跳轉(zhuǎn)請求之后再執(zhí)行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"***** 接收到服務(wù)器跳轉(zhuǎn)請求之后再執(zhí)行 *****");
}
// 在收到響應(yīng)后吵瞻,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSLog(@"***** 收到服務(wù)器響應(yīng)理疙,是否跳轉(zhuǎn) *****");
/*
WKNavigationResponsePolicyCancel,//不同意跳轉(zhuǎn)
WKNavigationResponsePolicyAllow,//同意跳轉(zhuǎn)
*/
decisionHandler(WKNavigationResponsePolicyAllow);
}
// 在發(fā)送請求之前,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSString *urlString = [[navigationAction.request URL] absoluteString];
urlString = [urlString stringByRemovingPercentEncoding];
NSLog(@"Requset URL = %@",urlString);
// 用'://'截取字符串
NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
if ([urlComps count]) {
// 獲取協(xié)議頭
NSString *protocolHead = [urlComps objectAtIndex:0];
NSLog(@"Protocol Header = %@",protocolHead);
}
/*
WKNavigationResponsePolicyCancel,//不同意跳轉(zhuǎn)
WKNavigationResponsePolicyAllow,//同意跳轉(zhuǎn)
*/
decisionHandler(WKNavigationActionPolicyAllow);
}
//1.創(chuàng)建一個新的WebVeiw
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
WKFrameInfo *frameInfo = navigationAction.targetFrame;
if (![frameInfo isMainFrame]) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
//2.WebVeiw關(guān)閉(9.0中的新方法)
- (void)webViewDidClose:(WKWebView *)webView{
NSLog(@"%s",__func__);
}
//3.顯示一個JS的Alert(與JS交互)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
// js 里面的alert實現(xiàn)催植,如果不實現(xiàn),網(wǎng)頁的alert函數(shù)無效
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
completionHandler();
}]];
[self presentViewController:alertController animated:YES completion:nil];
}
//4.彈出一個輸入框(與JS交互的)
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
completionHandler(@"Client Not handler");
}
//5.顯示一個確認框(JS的)
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
UIAlertController *alertCtl = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertCtl addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction*action){
completionHandler(YES);
}]];
[alertCtl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction*action){
completionHandler(NO);
}]];
[self presentViewController:alertCtl animated:YES completion:nil];
}
上面的全是WKWebView的代理方法
值得一提的是
//1.創(chuàng)建一個新的WebVeiw
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
WKFrameInfo *frameInfo = navigationAction.targetFrame;
if (![frameInfo isMainFrame]) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
這個方法在點擊H5頁面中的鏈接 跳轉(zhuǎn)的時候會調(diào)用 最開始的時候 我直接寫
return self.webView
運行 點擊的時候程序直接crash
報錯:
** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Returned WKWebView was not created with the given configuration.**
原因呢:
每次點擊H5中的line會跳轉(zhuǎn)一個新網(wǎng)頁勺择,"_black" 是開一個新的頁面 打開網(wǎng)頁,和Safari中點加號一樣创南!
當(dāng)然在應(yīng)用中如果不實現(xiàn)和Safari一樣的效果 那就只能讓其在當(dāng)前頁面中 重新加載一次新link
還有一種解決方法:
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//如果是跳轉(zhuǎn)一個新頁面
if (navigationAction.targetFrame == nil) {
[webView loadRequest:navigationAction.request];
}
decisionHandler(WKNavigationActionPolicyAllow);
}
進度條問題:
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
NSLog(@"new = %@ ;",change[@"new"]);
self.progressView.progress = [change[@"new"] floatValue];
}
if (self.progressView.progress == 0) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progressView.hidden = YES;
});
}
}
不要忘了 移除KVO的監(jiān)聽了!
WKWebView 與js 交互參考 http://www.reibang.com/p/c59dd41c3631