1. 程式人生 > >iOS WKWebView使用

iOS WKWebView使用

之前專案都是UIWebView實現的,最近改成了WKWebView ,下面一起學習下(含有demo):
一、WKWebView的優勢

  • 效能高,穩定性好,佔用的記憶體比較小,
  • 支援JS互動
  • 支援HTML5 新特性
  • 可以新增進度條

二、具體使用

1、首先需要匯入庫檔案

#import <WebKit/WebKit.h>

2、繼承代理事件

WKNavigationDelegate,WKUIDelegate 

3、建立WKWebView

- (WKWebView *)webView {
    if (!_webView) {
         // 進行配置控制器
         WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
         // 例項化物件
         configuration.userContentController = [WKUserContentController new];
         // 呼叫JS方法
        [configuration.userContentController addScriptMessageHandler:self name:@"uploadPersonImage"];
        //window.webkit.messageHandlers.uploadPersonImage.postMessage({body: 'goodsId=1212'}); js呼叫
        // 進行偏好設定
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptEnabled = YES;
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 40.0;
        configuration.preferences = preferences;
    
        _webView = [[WKWebView alloc] initWithFrame:RECT(0, heightWebView, SCREENWIDTH, SCREENHEIGHT- heightWebView) configuration:configuration];
        _webView.navigationDelegate = self;
        _webView.opaque = NO;
        _webView.backgroundColor = [UIColor whiteColor];
        if (@available(ios 11.0,*)){ _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;}
     }
     return _webView;
}

4、實現WKNavigationDelegate代理方法

// 頁面開始載入時呼叫
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    LHLog(@"頁面開始載入時呼叫");
    
}

// 當內容開始返回時呼叫
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    LHLog(@"當內容開始返回時呼叫");
}

// 頁面載入完成之後呼叫
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//這裡修改導航欄的標題,動態改變
    LHLog(@"頁面載入完成之後呼叫");
    
    
}
// 頁面載入失敗時呼叫
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    LHLog(@"頁面載入失敗時呼叫");
}
// 接收到伺服器跳轉請求之後再執行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    LHLog(@"接收到伺服器跳轉請求之後再執行");
}
// 在收到響應後,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    LHLog(@"在收到響應後,決定是否跳轉");
    LHLog(@"%@",navigationResponse);
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //這句是必須加上的,不然會異常
    decisionHandler(actionPolicy);
}
// 在傳送請求之前,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    LHLog(@"在傳送請求之前,決定是否跳轉");
    //這句是必須加上的,不然會異常
    decisionHandler(WKNavigationActionPolicyAllow);
    NSURL *requestURL = navigationAction.request.URL;
        LHLog(@"-----%@",requestURL.absoluteString);
}

5、實現WKUIDelegate代理事件,主要實現與js的互動

//顯示一個JS的Alert(與JS互動)

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
}

//彈出一個輸入框(與JS互動的)
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{     
}

//顯示一個確認框(JS的)

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
}

5、載入資料

  • 載入伺服器連結
    帶引數

    NSString * urlS = [NSString stringWithFormat:@"https://www.baidu.com?q=w"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlS]]];
    

    不帶引數

    NSString * urlS = [NSString stringWithFormat:@"https://www.baidu.com"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlS]]];
    
  • 載入本地的html 這樣有的會出現圖片樣式不顯示的情況, 解決辦法 : Added folders 選擇 Create folder
    references ;或者將檔案壓縮,拖到專案中,然後解壓到沙盒目錄下

    不帶引數

     NSString * pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"app/html"];    //app/html 是html檔案在專案中的目錄
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pathString]]];
    

    帶引數

    NSString * pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"app/html"];    //app/html 是html檔案在專案中的目錄
    NSString * urlString2 = [[NSString stringWithFormat:@"?sid=%@",GETUSERDEFAULT(@"cookie")]stringByAddingPercentEncodingWithAllowedCharacters:  [NSCharacterSet URLFragmentAllowedCharacterSet]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString2 relativeToURL:[NSURL fileURLWithPath:pathString]]]];
    
  • 載入沙盒

    帶引數

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/app/html/index.html"]];
    NSString * urlString2 = [[NSString stringWithFormat:@"?sid=%@",GETUSERDEFAULT(@"cookie")]stringByAddingPercentEncodingWithAllowedCharacters:    [NSCharacterSet URLFragmentAllowedCharacterSet]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString2 relativeToURL:[NSURL fileURLWithPath:path]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.f]];
    

    不帶引數

     NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString * path = [paths objectAtIndex:0];
     path = [path stringByAppendingString:[NSString stringWithFormat:@"/app/html/index.html"]];
     NSString * urlString1 = [[NSString stringWithFormat:@"%@",path] stringByAddingPercentEncodingWithAllowedCharacters:   [NSCharacterSet URLFragmentAllowedCharacterSet]];
    

以上就是WKwebView的具體使用 demo下載