iOS 開(kāi)發(fā)之 WKWebView

1、加載網(wǎng)頁(yè)

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:webView];

2、加載的狀態(tài)回調(diào) (WKNavigationDelegate)

// 頁(yè)面開(kāi)始加載時(shí)調(diào)用

  • (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
    // 當(dāng)內(nèi)容開(kāi)始返回時(shí)調(diào)用
  • (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
    // 頁(yè)面加載完成之后調(diào)用
  • (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
    // 頁(yè)面加載失敗時(shí)調(diào)用
  • (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;

頁(yè)面跳轉(zhuǎn)的代理方法:
// 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用

  • (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;
    // 在收到響應(yīng)后,決定是否跳轉(zhuǎn)
  • (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
    // 在發(fā)送請(qǐng)求之前,決定是否跳轉(zhuǎn)
  • (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

3、WKUIDelegate協(xié)議

這個(gè)協(xié)議主要用于WKWebView處理web界面的三種提示框(警告框、確認(rèn)框、輸入框)
/**

  • web界面中有彈出警告框時(shí)調(diào)用
  • @param webView 實(shí)現(xiàn)該代理的webview
  • @param message 警告框中的內(nèi)容
  • @param frame 主窗口
  • @param completionHandler 警告框消失調(diào)用
    */
  • (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(void (^)())completionHandler;

4、動(dòng)態(tài)加載并運(yùn)行JS代碼

用于在客戶(hù)端內(nèi)部加入JS代碼
// 圖片縮放的js代碼

NSString *js = @"var count = document.images.length;for (var i = 0; i < count; i++) {var image = document.images[i];image.style.width=320;};window.alert('找到' + count + '張圖');";
// 根據(jù)JS字符串初始化WKUserScript對(duì)象
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
// 根據(jù)生成的WKUserScript對(duì)象,初始化WKWebViewConfiguration
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addUserScript:script];
_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
[_webView loadHTMLString:@"<head></head><imgea src='http://www.nsu.edu.cn/v/2014v3/img/background/3.jpg' />"baseURL:nil];
[self.view addSubview:_webView];

5、webView 執(zhí)行JS代碼

用戶(hù)調(diào)用用JS寫(xiě)過(guò)的代碼
//javaScriptString是JS方法名,completionHandler是異步回調(diào)block
[self.webView evaluateJavaScript:javaScriptString completionHandler:completionHandler];

6、JS調(diào)用App注冊(cè)過(guò)的方法

再WKWebView里面注冊(cè)供JS調(diào)用的方法,是通過(guò)WKUserContentController類(lèi)下面的方法:

  • (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
    scriptMessageHandler是代理回調(diào),JS調(diào)用name方法后,OC會(huì)調(diào)用scriptMessageHandler指定的對(duì)象。
    JS在調(diào)用OC注冊(cè)方法的時(shí)候要用下面的方式:
    window.webkit.messageHandlers.<name>.postMessage(<messageBody>)
    //OC注冊(cè)供JS調(diào)用的方法
    [[_webView configuration].userContentController addScriptMessageHandler:self name:@"closeMe"];
    //OC在JS調(diào)用方法做的處理
  • (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
    {
    NSLog(@"JS 調(diào)用了 %@ 方法,傳回參數(shù) %@",message.name,message.body);
    }
    //JS調(diào)用
    window.webkit.messageHandlers.closeMe.postMessage(null);

7、更改 User-Agent

有時(shí)我們需要在User-Agent添加一些額外的信息,這時(shí)就要更改默認(rèn)的User-Agent在使用UIWebView的時(shí)候,可用如下代碼(在使用UIWebView之前執(zhí)行)全局更改User-Agent:
// 獲取默認(rèn)
User-AgentUIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
// 給User-Agent添加額外的信息 比如 app 名字
NSString *newAgent = [NSString stringWithFormat:@"%@%@", oldAgent, @"_app"];
// 設(shè)置 User-Agent
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

或者改為用 WKWebView 獲取默認(rèn)的User-Agent,代碼如下:
self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
// 獲取默認(rèn)
User-Agent[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *oldAgent = result;
// 給User-Agent添加額外的信息
NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"extra_user_agent"];
// 設(shè)置global User-Agent
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}];

8、刪除導(dǎo)航棧

當(dāng) webview 內(nèi)部跳轉(zhuǎn)打開(kāi)新的 h5 頁(yè)面,我們想刪除上一個(gè) h5 頁(yè)面
[wek.backForwardList performSelector:NSSelectorFromString(@"_removeAllItems")];

綜合使用

#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 設(shè)置偏好設(shè)置
    config.preferences = [[WKPreferences alloc] init];
    // 默認(rèn)為0
    config.preferences.minimumFontSize = 10;
    // 默認(rèn)認(rèn)為YES
    config.preferences.javaScriptEnabled = YES;
    // 在iOS上默認(rèn)為NO,表示不能自動(dòng)通過(guò)窗口打開(kāi)
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;

    // web內(nèi)容處理池,由于沒(méi)有屬性可以設(shè)置,也沒(méi)有方法可以調(diào)用,不用手動(dòng)創(chuàng)建
    config.processPool = [[WKProcessPool alloc] init];
    // 視屏內(nèi)聯(lián)播放
    config.allowsInlineMediaPlayback = YES;
    // 通過(guò)JS與webview內(nèi)容交互
    config.userContentController = [[WKUserContentController alloc] init];
    // 注入JS對(duì)象名稱(chēng)AppModel,當(dāng)JS通過(guò)AppModel來(lái)調(diào)用時(shí),
    // 我們可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:@"AppModel"];

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
                                      configuration:config];
    [self.view addSubview:self.webView];

    // 導(dǎo)航代理
    self.webView.navigationDelegate = self;
    // 與webview UI交互代理
    self.webView.UIDelegate = self;

//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];


    NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:path]];

    // 添加KVO監(jiān)聽(tīng)
    [self.webView addObserver:self
                   forKeyPath:@"loading"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];

#pragma mark - WKUIDelegate
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_9_0
- (void)webViewDidClose:(WKWebView *)webView {
    NSLog(@"%s", __FUNCTION__);
}
#endif

// 創(chuàng)建一個(gè)新的WebView(標(biāo)簽帶有 target='_blank' 時(shí),導(dǎo)致WKWebView無(wú)法加載點(diǎn)擊后的網(wǎng)頁(yè)的問(wèn)題。)
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    // 接口的作用是打開(kāi)新窗口委托
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

// 在JS端調(diào)用alert函數(shù)時(shí),會(huì)觸發(fā)此代理方法。
// JS端調(diào)用alert時(shí)所傳的數(shù)據(jù)可以通過(guò)message拿到
// 在原生得到結(jié)果后,需要回調(diào)JS,是通過(guò)completionHandler回調(diào)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調(diào)用alert" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];

    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"%@", message);
}

// JS端調(diào)用confirm函數(shù)時(shí),會(huì)觸發(fā)此方法
// 通過(guò)message可以拿到JS端所傳的數(shù)據(jù)
// 在iOS端顯示原生alert得到Y(jié)ES/NO后
// 通過(guò)completionHandler回調(diào)給JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    NSLog(@"%s", __FUNCTION__);

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS調(diào)用confirm" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];

    NSLog(@"%@", message);
}

// JS端調(diào)用prompt函數(shù)時(shí),會(huì)觸發(fā)此方法
// 要求輸入一段文本
// 在原生輸入得到文本內(nèi)容后,通過(guò)completionHandler回調(diào)給JS
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
    NSLog(@"%s", __FUNCTION__);

    NSLog(@"%@", prompt);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS調(diào)用輸入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }];

    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];

    [self presentViewController:alert animated:YES completion:NULL];
}
#pragma mark - WKNavigationDelegate

#pragma mark - WKNavigationDelegate
/**
 *  在發(fā)送請(qǐng)求之前,決定是否跳轉(zhuǎn)
 *
 *  @param webView          實(shí)現(xiàn)該代理的
 *  @param navigationAction 當(dāng)前navigation
 *  @param decisionHandler  是否調(diào)轉(zhuǎn)block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && ![hostname containsString:@".baidu.com"]) {
        // 對(duì)于跨域,需要手動(dòng)跳轉(zhuǎn)
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];

        // 不允許web內(nèi)跳轉(zhuǎn)
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
       self.progressView.alpha = 1.0;
        decisionHandler(WKNavigationActionPolicyAllow);
    }

    NSLog(@"%s", __FUNCTION__);
}

/**
 *  在收到響應(yīng)后,決定是否跳轉(zhuǎn)
 *
 *  @param webView            實(shí)現(xiàn)該代理的webview
 *  @param navigationResponse 當(dāng)前navigation
 *  @param decisionHandler    是否跳轉(zhuǎn)block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {

    //    NSLog(@"%@",navigationResponse.response);

    // 如果響應(yīng)的地址是百度,則允許跳轉(zhuǎn)
    //    if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
    //
    //        // 允許跳轉(zhuǎn)
    //        decisionHandler(WKNavigationResponsePolicyAllow);
    //        return;
    //    }
    //    // 不允許跳轉(zhuǎn)
    //    decisionHandler(WKNavigationResponsePolicyCancel);
    decisionHandler(WKNavigationResponsePolicyAllow);
}

/**
 *  頁(yè)面開(kāi)始加載時(shí)調(diào)用
 *
 *  @param webView    實(shí)現(xiàn)該代理的webview
 *  @param navigation 當(dāng)前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用
 *
 *  @param webView      實(shí)現(xiàn)該代理的webview
 *  @param navigation   當(dāng)前navigation
 */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  加載失敗時(shí)調(diào)用
 *
 *  @param webView    實(shí)現(xiàn)該代理的webview
 *  @param navigation 當(dāng)前navigation
 *  @param error      錯(cuò)誤
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  當(dāng)內(nèi)容開(kāi)始返回時(shí)調(diào)用
 *
 *  @param webView    實(shí)現(xiàn)該代理的webview
 *  @param navigation 當(dāng)前navigation
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  頁(yè)面加載完成之后調(diào)用
 *
 *  @param webView    實(shí)現(xiàn)該代理的webview
 *  @param navigation 當(dāng)前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
}

// 導(dǎo)航失敗時(shí)會(huì)回調(diào)
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {

}

// 對(duì)于HTTPS的都會(huì)觸發(fā)此代理,如果不要求驗(yàn)證,傳默認(rèn)就行
// 如果需要證書(shū)驗(yàn)證,與使用AFN進(jìn)行HTTPS證書(shū)驗(yàn)證是一樣的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}

// 9.0才能使用,web內(nèi)容處理中斷時(shí)會(huì)觸發(fā)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"%s", __FUNCTION__);
}

// 從web界面中接收到一個(gè)腳本時(shí)調(diào)用
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"AppModel"]) {
        // 打印所傳過(guò)來(lái)的參數(shù),只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull類(lèi)型
        NSLog(@"======>%@", message.body);
    }
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"loading"]) {
        NSLog(@"loading");
    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"progress: %f", self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
    }

    // 加載完成
    if (!self.webView.loading) {
        // 手動(dòng)調(diào)用JS代碼
        // 每次頁(yè)面完成都彈出來(lái),大家可以在測(cè)試時(shí)再打開(kāi)
        NSString *js = @"callJsAlert()";
        [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            NSLog(@"response: %@ error: %@", response, error);
            NSLog(@"call js alert by native");
        }];

        NSString *jsData = @"calltoValue('參數(shù)')";
        [self.webView evaluateJavaScript:jsData completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            NSLog(@"response: %@ error: %@", response, error);
            NSLog(@"------->call js alert by native");
        }];


        [UIView animateWithDuration:0.5 animations:^{
          self.progressView.alpha = 0;
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
<!DOCTYPE html>
<html>
    <head>
        <title>iOS and Js</title>
        <style type="text/css">
            * {
                font-size: 40px;
            }
        </style>
    </head>

    <body>

        <div style="margin-top: 100px">
            <h1>Test how to use objective-c call js</h1><br/>
            <div><input type="button" value="call js alert" onclick="callJsAlert()"></div>
            <br/>
            <div><input type="button" value="Call js confirm" onclick="callJsConfirm()"></div><br/>
        </div>
        <br/>
        <div>
            <div><input type="button" value="Call Js prompt " onclick="callJsInput()"></div><br/>
            <div>Click me here: <a >Jump to Baidu</a></div>
        </div>

        <br/>
        <div id="SwiftDiv">
            <span id="jsParamFuncSpan" style="color: red; font-size: 50px;"></span>
        </div>

        <script type="text/javascript">
            function callJsAlert() {
                alert('Objective-C call js to show alert');

                window.webkit.messageHandlers.AppModel.postMessage({body: 'call js alert in js'});
            }

        function callJsConfirm() {
            if (confirm('confirm', 'Objective-C call js to show confirm')) {
                document.getElementById('jsParamFuncSpan').innerHTML
                = 'true';
            } else {
                document.getElementById('jsParamFuncSpan').innerHTML
                = 'false';
            }

            // AppModel是我們所注入的對(duì)象
            window.webkit.messageHandlers.AppModel.postMessage({body: 'call js confirm in js'});
        }


        function calltoValue(data){

            window.webkit.messageHandlers.AppModel.postMessage({body:data})
        }


        function callJsInput() {
            var response = prompt('Hello', 'Please input your name:');
            document.getElementById('jsParamFuncSpan').innerHTML = response;

            // AppModel是我們所注入的對(duì)象
            window.webkit.messageHandlers.AppModel.postMessage({body: response});
        }
        </script>
    </body>
</html>

來(lái)源
http://www.cocoachina.com/ios/20161122/18162.html
http://www.cnblogs.com/wanglizhi/p/5892813.html
http://www.itdecent.cn/p/6ba2507445e4

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

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

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