iOS開(kāi)發(fā)中webview和OC交互

1.簡(jiǎn)介

iOS開(kāi)發(fā)中不可避免會(huì)遇到跟H5界面的問(wèn)題,本文將詳細(xì)講解OC和web的交互,供大家學(xué)習(xí)參考。

2.概述

2.1交互方式

  • OC調(diào)用JS
  • JS調(diào)用OC

2.2加載JS的方式

OC開(kāi)發(fā)中加載網(wǎng)頁(yè)有兩種選擇,iOS7之前使用UIWebView,iOS8之后時(shí)候WKWebView,后續(xù)將分別講解UIWebView和WKWebView如何和網(wǎng)頁(yè)交互實(shí)現(xiàn)JS和OC的相互調(diào)用。

2.3網(wǎng)頁(yè)中加載框顯示異常

主要有如下兩個(gè)問(wèn)題

  • 提示框無(wú)法顯示
  • 提示框標(biāo)題顯示異常

3.UIWebView和網(wǎng)頁(yè)的交互

3.1原生OC調(diào)用網(wǎng)頁(yè)的JS

[_web stringByEvaluatingJavaScriptFromString:@"callJS('ok');" ];
以上代碼即可實(shí)現(xiàn)webView調(diào)用網(wǎng)頁(yè),其中的callJS為js的方法,ok是傳入的參數(shù)

3.2網(wǎng)頁(yè)JS調(diào)用原生OC的方法

3.2.1 攔截請(qǐng)求

OC端代碼

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@":"];
    //攔截UIWebView請(qǐng)求的URL,根據(jù)不同的規(guī)則,可以調(diào)用不同的OC方法
    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"])
    {
        [self back];
        return false;
    }
    return true;
}
- (void)back
{
    [self dismissViewControllerAnimated:true completion:^{
        
    }];
}

JS端代碼

在這里插入代碼片
function clickLink(){
            var url="testapp:"+"alert"+":"+"你好嗎?";
            document.location = url;
        }

3.3.2 注入JS代碼

OC端代碼

 [self.web stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function myFunction() { "   //定義myFunction方法
     "alert('注入js');"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];  
     OC代碼中自定義JS方法myFunction注入到網(wǎng)頁(yè)中,JS端可以直接調(diào)用myFunction方法。由于該方法是OC中注入的,故而可以傳入一定的參數(shù)用于網(wǎng)頁(yè)端和OC端的通信。

JS端代碼

function callInjeJs(){
            myFunction();
        }

4.WKWebView和網(wǎng)頁(yè)的交互

4.1.原生OC調(diào)用網(wǎng)頁(yè)的JS

OC端代碼

 [_web evaluateJavaScript:@"callJS('ok')" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    }];
 以上代碼即可實(shí)現(xiàn)webView調(diào)用網(wǎng)頁(yè),其中的callJS為js的方法,ok是傳入的參數(shù)

JS端代碼

 function callJS(str1)
        {
            alert(str1);
        }

4.2.網(wǎng)頁(yè)JS調(diào)用原生OC的方法

OC端代碼

 WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
 [config.userContentController addScriptMessageHandler:self name:@"AppModel"];
 WKWebView *web = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0,400, 250) configuration:config];
  [self.view addSubview:web];
    
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSString *name = message.name;
    if([name isEqualToString:@"AppModel"])
    {
        NSString *bodyStr = message.body;
        NSLog(@"JS調(diào)用OC成功 參數(shù)為= %@",bodyStr);
    }
}
該方法為WKScriptMessageHandler的協(xié)議方法,務(wù)必遵守該協(xié)議

JS端代碼

 function callOC()
        {
            window.webkit.messageHandlers.AppModel.postMessage({body: 'param1'});
        }
        其中AppModel為名稱(chēng),{body,'param1'}為自定義的參數(shù)

5.JS提示框顯示異常問(wèn)題

5.1.JS提示框在UIWebView中顯示異常

JS提示框在UIWebView顯示時(shí),經(jīng)常會(huì)出現(xiàn)一個(gè)URL的地址,在其他客戶端(如安卓)沒(méi)有此問(wèn)題。該問(wèn)題可通過(guò)如下代碼解決:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //獲取js寫(xiě)的界面的title
        NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    //*解決webview上內(nèi)嵌的頁(yè)面中彈出來(lái)的alert有域名問(wèn)題!*/ PS:這個(gè)才是這篇博客的關(guān)鍵
    //1、獲取js的執(zhí)行環(huán)境
    JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //2、js那邊寫(xiě)的提示框的函數(shù)入口,這里差不多有點(diǎn)重寫(xiě)那個(gè)函數(shù)的意思。JSValue *message參數(shù)可以獲取到j(luò)s中的提示信息,OC中需要轉(zhuǎn)換為string顯示出來(lái),好了完成了。
    //解決Alert類(lèi)型的提示框異常問(wèn)題
    ctx[@"window"][@"alert"] = ^(JSValue *message) {
        dispatch_async(dispatch_get_main_queue(), ^{
        //自定義原生提示框替換原來(lái)的提示框
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:[message toString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        });
    };
    //解決confirm提示框顯示異常問(wèn)題
    ctx[@"window"][@"confirm"]=^(JSValue *message) {
        dispatch_async(dispatch_get_main_queue(), ^{
          //自定義原生提示框替換原來(lái)的提示框
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:[message toString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        });
    };
    //解決prompt提示框顯示異常問(wèn)題
    ctx[@"window"][@"prompt"] = ^(JSValue *message) {
        dispatch_async(dispatch_get_main_queue(), ^{
          //自定義原生提示框替換原來(lái)的提示框
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:[message toString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        });
    };
}

5.2. JS提示框在WKWebView中顯示異常

JS提示框在WKWebView中會(huì)無(wú)法顯示,可以通過(guò)以下的方案解決。

// 在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:message 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];
}

6 總結(jié)

本文針對(duì)ios開(kāi)發(fā)中webview和網(wǎng)頁(yè)的交互問(wèn)題做了簡(jiǎn)單總結(jié),后續(xù)有任何問(wèn)題還會(huì)更新。如果各位有任何問(wèn)題,歡迎回復(fù)。

源碼地址

?著作權(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)容