ios WKWebView和js交互

WKWebViewConfiguration注入WKScriptMessageHandler,由前端下發(fā)數(shù)據(jù),客戶端根據(jù)相關(guān)的數(shù)據(jù)作出相應(yīng)的操作,OC代碼如下:

  • wkWebView懶加載
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        // 進行配置控制器
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        // 實例化對象
        configuration.userContentController = [WKUserContentController new];
        // 調(diào)用JS方法
        [configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
        
        // 進行偏好設(shè)置
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
//        preferences.minimumFontSize = 20.0;
        configuration.preferences = preferences;
        
        // 初始化WKWebView
        _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
        
        _wkWebView.UIDelegate = self;
        
        _wkWebView.navigationDelegate =self;
        
    }
    return _wkWebView;
}
  • 添加到當前視圖上,并加載相應(yīng)的鏈接
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
  • 遵守相應(yīng)的協(xié)議
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

//webView
@property (nonatomic, strong) WKWebView *wkWebView;

@end

  • 實現(xiàn)WKScriptMessageHandler代理方法,并在該代理方法中根據(jù)相應(yīng)的注入js的名稱,實現(xiàn)對應(yīng)的邏輯
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"NativeModel"]) {
        NSDictionary *jsData = message.body;
        NSLog(@"%@", message.name);
        //讀取js function的字符串
//        NSString *jsFunctionString = jsData[@"result"];
//        //拼接調(diào)用該方法的js字符串(convertDictionaryToJson:方法將NSDictionary轉(zhuǎn)成JSON格式的字符串)
//        NSString *jsonString = [NSDictionary convertDictionaryToJson:@{@"test":@"123", @"data":@"666"}];
//        NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", jsFunctionString, jsonString];
//        //執(zhí)行回調(diào)
//        [self.weWebView evaluateJavaScript:jsCallBack completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//            if (error) {
//                NSLog(@"err is %@", error.domain);
//            }
//        }];
    }
}

前端代碼如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>html5page-oc</title>

    <script>
        function btn1Click() {
            window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
            alert("after call");
        }
    </script>

</head>
<body>

<input type="button" value="button c" onclick="btn1Click()">

</body>
</html>

使用WKWebViewjs傳值

OC代碼如下

  • wkWebView懶加載
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        // 進行配置控制器
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        // 實例化對象
        configuration.userContentController = [WKUserContentController new];
        // 調(diào)用JS方法
        [configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
        
        // 進行偏好設(shè)置
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
//        preferences.minimumFontSize = 20.0;
        configuration.preferences = preferences;
        
        // 初始化WKWebView
        _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
        
        _wkWebView.UIDelegate = self;
        
        _wkWebView.navigationDelegate =self;
        
    }
    return _wkWebView;
}
  • 添加到當前視圖上,并加載相應(yīng)的鏈接
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
  • 遵守相應(yīng)的協(xié)議
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

//webView
@property (nonatomic, strong) WKWebView *wkWebView;

@end

  • 實現(xiàn)代理方法,在協(xié)議加載完WebView后,注入相應(yīng)的js,將需要上傳的參數(shù)上傳給前端
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"username"] = @"里斯";
    dic[@"token"] = @"1198203";
    dic[@"avatar"] = @"";
    
    NSString *jsonStr = [self convertToJsonData:dic];
    
    NSString * jsStr = [NSString stringWithFormat:@"sendKey('%@')",jsonStr];
    
    [self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        //此處可以打印error.
        
        
    }];
}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的換行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

前端代碼如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div onclick="newway()">新方法</div>
    <input type="text" id = "show1">
    <input type="text" id = "show2">
    <input type="text" id = "show3">
</body>
<script src="js/jquery-2.1.4.js"></script>
<script>
  function newway(){
    alert("newway")
    // var val = '{"token":"1198203","username":"張三","avatar":""}'
    // sendKey(val)
  }

  function sendKey(val){
    alert("sendKey")
    let iOSInfo = JSON.parse(val);

    $("#show1").val(iOSInfo.username)
    $("#show2").val(iOSInfo.token)
    $("#show3").val(iOSInfo.avatar)

  }
 
</script>
</html>

遇到的問題

  • 上傳參數(shù)到前端,注入js時出現(xiàn)Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred錯誤,檢查上傳的JSON是否正確,保證上傳的JSON是一個正確的JSON即可
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末尺铣,一起剝皮案震驚了整個濱河市拴曲,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌凛忿,老刑警劉巖澈灼,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異店溢,居然都是意外死亡叁熔,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門床牧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來荣回,“玉大人,你說我怎么就攤上這事戈咳⌒娜恚” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵著蛙,是天一觀的道長糯累。 經(jīng)常有香客問我,道長册踩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任效拭,我火速辦了婚禮暂吉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘缎患。我一直安慰自己慕的,他們只是感情好,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布挤渔。 她就那樣靜靜地躺著肮街,像睡著了一般。 火紅的嫁衣襯著肌膚如雪判导。 梳的紋絲不亂的頭發(fā)上嫉父,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天沛硅,我揣著相機與錄音,去河邊找鬼绕辖。 笑死摇肌,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的仪际。 我是一名探鬼主播围小,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼树碱!你這毒婦竟也來了肯适?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤成榜,失蹤者是張志新(化名)和其女友劉穎框舔,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體伦连,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡雨饺,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了惑淳。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片额港。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖歧焦,靈堂內(nèi)的尸體忽然破棺而出移斩,到底是詐尸還是另有隱情,我是刑警寧澤绢馍,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布向瓷,位于F島的核電站,受9級特大地震影響舰涌,放射性物質(zhì)發(fā)生泄漏猖任。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一瓷耙、第九天 我趴在偏房一處隱蔽的房頂上張望朱躺。 院中可真熱鬧,春花似錦搁痛、人聲如沸长搀。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽源请。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谁尸,已是汗流浹背舅踪。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留症汹,地道東北人硫朦。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像背镇,于是被迫代替她去往敵國和親咬展。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容