JS和原生交互

現(xiàn)在H5和原生的交互在日常開發(fā)中經(jīng)常用的,很多APP為了優(yōu)化APP,更加便捷靈活的更新頁面,有很多頁面交給了H5來開發(fā),那么JS和原生的交互就很重要了。

現(xiàn)在常用的主要有兩種方式:第三方WebViewJavascriptBridge和原生的交互

首先先來講一下第一種WebViewJavascriptBridge

首先要引入WebViewJavascriptBridge,可以用cocoapods來引入

pod 'WebViewJavascriptBridge'

可以新建一個工具類然后引入

#import <WebViewJavascriptBridge.h>

@property (nonatomic, strong) WebViewJavascriptBridge *bridge;
@property(nonatomic,strong)WKWebView * webView;


然后和webview建立關(guān)系

- (void)configureWithWebView:(WKWebView *)webView {
    self.webView = webView;
    // 3.開啟日志
    [WebViewJavascriptBridge enableLogging];
    
    // 4.給webView建立JS和OC的溝通橋梁
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
    [self.bridge setWebViewDelegate:self];
    
}
這里是JS調(diào)用OC的API:訪問相冊
-(void)openCamera{
    /* JS調(diào)用OC的API:訪問相冊 */
//    self.Controller = [self getCurrentViewController];
    [self.bridge registerHandler:@"openCamera" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"需要%@圖片", data[@"count"]);
        
//        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
//        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController * picker =[[UIImagePickerController alloc] init];
            picker.delegate = self;
            //設(shè)置拍照后的圖片可被編輯
            picker.allowsEditing = YES;
//            picker.sourceType = sourceType;
        self.Controller = [self getCurrentViewController];
            //        [self presentModalViewController:picker animated:YES];被廢棄的
            [self.Controller presentViewController:picker animated:YES completion:nil];
//        }
    }];
    
    
     /* JS調(diào)用OC的API:訪問底部彈窗 */
    [self.bridge registerHandler:@"showSheet" handler:^(id data, WVJBResponseCallback responseCallback) {
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"你猜我出不出來?" message:@"嘻嘻嘻嘻!!" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [vc addAction:cancelAction];
        [vc addAction:okAction];
        [[self getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    }];
}

在Controller頁面創(chuàng)建一個webview


 self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 300)];
    [self.view addSubview:self.webView];
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 600, 100, 100)];
    [self.view addSubview:self.imageView];

NSString *indexPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString *appHtml = [NSString stringWithContentsOfFile:indexPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseUrl = [NSURL fileURLWithPath:indexPath];
    [self.webView loadHTMLString:appHtml baseURL:baseUrl];
    [[HLWebTool HLWebToolAPI] configureWithWebView:self.webView];

    [[HLWebTool HLWebToolAPI] openCamera];//這個方法要調(diào)用的

index中的代碼

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
        <style>
            body{
                background-color:paleturquoise;
            }

            button{
                border:0;
                width: 150px;
                height: 35px;
                background-color: orangered;
                color: white;
                font-size: 16px;
                border-radius: 6px;
            }
        </style>
    </head>
    
    <body>
        <h2>JS調(diào)用OC中的方法</h2>
        <button id="btn">訪問OC相冊</button>
        <button id="btn1">調(diào)用OC提示窗</button>
        <p></p>
    </body>
    <script>
       // 這段代碼是固定的,必須要放到j(luò)s中
       function setupWebViewJavascriptBridge(callback) {
            if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
            if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
            window.WVJBCallbacks = [callback];
            var WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
        }
    
        // 與OC交互的所有JS方法都要在這里注冊,才能讓OC和JS之間相互調(diào)用
       setupWebViewJavascriptBridge(function(bridge) {

           /* JS給OC提供公開的API, 在OC中可以手動調(diào)用此API, 并且可以接收OC中傳過來的參數(shù),同時可回調(diào)OC */

           // 獲取用戶信息
           bridge.registerHandler('getUserInfo', function(data, responseCallback) {
               console.log("OC中傳遞過來的參數(shù):", data);
               // 把處理好的結(jié)果返回給OC
               responseCallback({"userID":"DX001", "userName":"旋之華", "age":"18", "otherName":"旋之華"})
           });

           //  彈框輸出
           bridge.registerHandler('alertMessage', function(data, responseCallback) {
               alert(data);
               console.log(data);
           });

           //  動態(tài)跳轉(zhuǎn)到京東商城
           bridge.registerHandler('pushToNewWebSite', function(data, responseCallback) {
               window.location.href = data.url;
           });

           bridge.registerHandler('insertImgToWebPage', function(data, responseCallback) {

                var img = document.createElement('img');
                img.src = data.url;
                img.width = 200;
                document.body.appendChild(img);

           });


           /* OC給JS提供公開的API, 在JS中可以手動調(diào)用此API, 并且可以接收OC中傳過來的參數(shù),同時可回調(diào)OC */
                                    
           // 調(diào)用OC中的打開相冊方法
           document.getElementById('btn').onclick = function () {
               bridge.callHandler('openCamera', {'count':'10張'}, function responseCallback(responseData) {
                   console.log("OC中返回的參數(shù):", responseData)
               });
           };

           document.getElementById('btn1').onclick = function () {
               bridge.callHandler('showSheet', '', function responseCallback(responseData) {
                   console.log("OC中返回的參數(shù):", responseData)
               });
           };
       })
    </script>
</html>

以上是JS調(diào)用OC的方法,接下來講OC調(diào)用JS


Controller里面添加點擊方法
UIButton * userBut = [[UIButton alloc] initWithFrame:CGRectMake(0, 50, 100, 50)];
    [self.view addSubview:userBut];
    [userBut setTitle:@"獲取用戶信息" forState:(UIControlStateNormal)];
    [userBut addTarget:self action:@selector(getUserinfo) forControlEvents:(UIControlEventTouchUpInside)];
///*  獲取用戶信息  */
- (void)getUserinfo {
    // 調(diào)用JS中的API
    [[HLWebTool HLWebToolAPI] getUserinfo];
    
}


工具類中實現(xiàn)方法
- (void)getUserinfo {
    // 調(diào)用JS中的API
    [self.bridge callHandler:@"getUserInfo" data:@{@"userId":@"DX001"} responseCallback:^(id responseData) {
        NSString *userInfo = [NSString stringWithFormat:@"%@,姓名:%@,年齡:%@", responseData[@"userID"], responseData[@"userName"], responseData[@"age"]];
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"從網(wǎng)頁端獲取的用戶信息" message:userInfo preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [vc addAction:cancelAction];
        [vc addAction:okAction];
        [[self getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    }];
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • 參考 總評: oc 與js的交互,1.有原生的方式,oc 調(diào)js簡單,js調(diào)oc 麻煩(協(xié)議攔截"實現(xiàn)的交互方式)...
    楊大蝦閱讀 402評論 0 3
  • 像我們在開發(fā)App的過程中難免會遇到App與前端H5的交互,那么我們就會碰到webView這樣的控件,但是與前端J...
    陳先生的干貨店閱讀 1,057評論 0 2
  • 在項目開發(fā)中,我們常常遇到這種情況,一個功能性界面需要分享到其他平臺,或者是一個較復雜,原生框架不易實現(xiàn),需要經(jīng)常...
    zhangferry閱讀 4,582評論 7 25
  • 需求說明 目前的APP客戶端內(nèi),經(jīng)常需要嵌入H5頁面進行混合開發(fā)。這樣,在開發(fā)過程中就會涉及到原生客戶端和H5交互...
    kobe55閱讀 1,393評論 0 3
  • 隨著H5技術(shù)的興起,在iOS開發(fā)過程中,難免會遇到原生應(yīng)用需要和H5頁面交互的問題。其中會涉及方法調(diào)用及參數(shù)傳值等...
    Chris_js閱讀 3,236評論 1 8

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