Ios開發之 -- js和ios的互動

來源:互聯網
上載者:User

標籤:blog   http   color   io   os   ar   使用   java   for   

==WebViewJavascriptBridge的介紹==

 


#下載:https://github.com/marcuswestin/WebViewJavascriptBridge
#關於WebViewJavascriptBridge的介紹:http://blog.csdn.net/yanghua_kobe/article/details/8209751
==WebViewJavascriptBridge(在與現有的業務代碼結合使用中)的小問題==
*demo部分(  ExampleApp.html介面中第50行):
 
       bridge.callHandler(‘testObjcCallback‘, {‘foo‘: ‘bar‘}, function(response) {


       由於底層回傳是兩個參數responseCallback(message.error, message.responseData) ,因此reponse對應的是message.error,此demo中得到的是undefinded;
 
  
*源碼實現部分(webview載入回調事件webViewDidFinishLoad):
   
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (webView != _webView) { return; }


    if (![[_webView stringByEvaluatingJavaScriptFromString:@"typeof WebViewJavascriptBridge == ‘object‘"] isEqualToString:@"true"]) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WebViewJavascriptBridge.js" ofType:@"txt"];
        NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [_webView stringByEvaluatingJavaScriptFromString:js];
    }
    
    if (self.startupMessageQueue) {
        for (id queuedMessage in self.startupMessageQueue) {
            [self _dispatchMessage:queuedMessage];
        }
        self.startupMessageQueue = nil;
    }
    
    if (self.webViewDelegate && [self.webViewDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [self.webViewDelegate webViewDidFinishLoad:webView];
    }
}


WebViewJavascriptBridge的使用流程中要將webview的delegate首先設定為自身,這是必須條件,
如果現有的業務代碼中需要使用webview的回調事件,則需要在初始化WebViewJavascriptBridge時制定業務代碼自身為後續的delegate;
在設定後續delegate之後,會出現問題;


以上代碼會造成webViewDidFinishLoad被調用兩次:業務代碼中設定webview的回調事件,而以上代碼中引入.js.txt資源,資源裡有對dom的直接修改,也會觸發webViewDidFinishLoad回呼函數;
由此造成業務代碼中的webViewDidFinishLoad會被執行兩次,形成錯誤或者不必要的多次調用;


處理:在js.txt資源引入之前不執行後續的代碼處理,即阻止第一次的viewdidload的後續調用,修改後如下:


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    if (webView != _webView) { return; }
    if (![[_webView stringByEvaluatingJavaScriptFromString:@"typeof WebViewJavascriptBridge == ‘object‘"] isEqualToString:@"true"]) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WebViewJavascriptBridge.js" ofType:@"txt"];
        NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [_webView stringByEvaluatingJavaScriptFromString:js];
    }
    //2012-12-3 對於源碼的變動,在js.txt載入之前,對於業務後續調用,不處理;
    else{
        if (self.startupMessageQueue) {
            for (id queuedMessage in self.startupMessageQueue) {
                [self _dispatchMessage:queuedMessage];
            }
            self.startupMessageQueue = nil;
        }
        if (self.webViewDelegate && [self.webViewDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
            [self.webViewDelegate webViewDidFinishLoad:webView];
        }
    }
}
 
*源碼部分(初始化函數):nil不能作為NSdictionary的value;

錯誤:
- (void)callHandler:(NSString *)handlerName {
    [self callHandler:handlerName data:nil responseCallback:nil];
}
正確:
- (void)callHandler:(NSString *)handlerName {
    [self callHandler:handlerName data:[NSNull null] responseCallback:nil];
}



==WebViewJavascriptBridge的使用==
===js和ios互動的直接代碼實現===
*jos對於js的調用:

[self.paperQuestionsShowWebview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setQuestionContent(‘%@‘)",qTitle]];

*js對於ios的調用:

在html js代碼中改變當前window的href;


    window.location.href="selfEvaluate/"+value;


以上事件觸發webview的shouldStartLoadWithRequest的回調事件;


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
   
    NSString *relativePath = request.mainDocumentURL.relativePath;
    if ([relativePath hasSuffix:@".html"]) {
        return YES;
    }
    else{
        NSRange doingRange = [relativePath rangeOfString:@"/doing/"];
        if (doingRange.length>0) {
            //擷取使用者選擇的選項
            NSString *userNewChoice = [relativePath substringFromIndex:doingRange.location+doingRange.length];
            //更新選項內容到伺服器端
            //判斷當前選項跟已經提交到伺服器端的時候一致,如果不一致,則提交到伺服器端
            if (![userNewChoice isEqualToString:self.currentQuestionAnswer]) {
                [self.delegate updateQuestionUserChoiceWithPid:self.paperId questionSequence:self.currentQuestionSequence choice:userNewChoice
 remainTime:self.reimainTime sender:self];
                //NSLog(@"update");
            }
        }
        else{
            .....
        }
        return NO;
    }
}



===js和ios互動的(WebViewJavascriptBridge)代碼實現===
*ios端的實現:
 
  引入標頭檔:
  #import "WebViewJavascriptBridge.h";
 
 
  指定WebViewJavascriptBridge 屬性:
   @property (strong, nonatomic) WebViewJavascriptBridge *javascriptBridge;
 
 
  初始化 WebViewJavascriptBridge;
    _javascriptBridge = [WebViewJavascriptBridge bridgeForWebView:_paperQuestionsShowWebview webViewDelegate:self handler:nil];
 

  註冊函數;
    [_javascriptBridge registerHandler:@"setSubjectiveQuestionScore" handler:^(id data, WVJBResponse *response){
            //擷取使用者選擇的選項
             NSInteger userScoreChoice = [(NSString *)data integerValue];
            //更新選項內容到伺服器端
            //判斷當前選項跟已經提交到伺服器端的時候一致,如果不一致,則提交到伺服器端
            
            //如果選擇新的分數,則同步到伺服器端
            if (userScoreChoice!=self.currentQuestionScore) {
                [self.delegate updateQuestionUserChooseScoreWithPid:self.paperId questionSequence:self.currentQuestionSequence score:userScoreChoice sender:self];
            }
        }];
 
 
  調用js代碼;
   [_javascriptBridge callHandler:@"setRightAnswer" data:qAnswer ];
 
 
*js的實現:
 
  必要的事件註冊和初始化:
   document.addEventListener(‘WebViewJavascriptBridgeReady‘, onBridgeReady, false);
   function onBridgeReady(event) {
                var bridge = event.bridge;
                //調用初始化函數,取消隊列,使訊息能夠得到直接處理;
                bridge.init(function(message) {
                            alert(message);
                            });
   }
 
 
  註冊函數:
   function onBridgeReady(event) {
             ......
                 bridge.registerHandler(‘setQuestionContent‘,function(content){


                               var e_content = document.getElementByIdx_x(‘qcontent‘);
                              e_content.innerHTML= content;
                                       
                });
   }
 
 
  實現js對ios的調用:
      newChoiceElement.onclick = function(){
               bridge.callHandler(‘choose‘,this.value);
       }
 


===js和ios互動的(WebViewJavascriptBridge)代碼實現中需要注意的問題===
#ios端必須保障架構中ios的實現作為webview的delegate,而業務代碼作為後續的delegate處理在初始化中加入;不然訊息得不到傳遞(會加入一個隊列,但是不會觸發訊息傳遞);
#js端必須實現init函數,不然訊息得不到傳遞(會加入一個隊列,但是不會觸發訊息傳遞);
#關於參數(ios端):單個的對象可以直接傳遞(int等基礎類型需要轉換成對應的對象);多值傳遞需要組成NSDictionary進行傳遞;
#關於參數(js端):單個對象直接傳遞;多值組成json格式字串{‘aa‘:‘ss‘,‘sdd‘:‘rrr‘};
#js文法以及編輯器對於錯誤的指示不明顯,造成一些字元或標點錯誤,以及文法不完成的錯誤很難被發現,是消耗時間比較長的地方,需要通過尋找更加完善的js編輯器解決;


===代碼引入WebViewJavascriptBridge實現ios和js互動的好處===
#協議:自己實現,在通訊的部分需要自己構建傳遞通訊協定,多人實現造成構建的傳遞通訊協定不同,比較容易混亂,採用統一的底層架構,可以減少這個問題;
#傳遞對象的字元轉義:架構對這塊又處理,不用自己再對一些字元進行轉移;
#架構封裝了js和ios的多次互動,在實現比較複雜的互動時比較有用,這塊如果開發人員自己實現,則代碼品質難控制,而且有一定的工作量;

document:屬性

document.title //設定文檔標題等價於HTML的
document.bgColor //設定頁面背景色
document.fgColor //設定前景色彩(文本顏色)
document.linkColor //未點擊過的連結顏色
document.alinkColor //啟用連結(焦點在此連結上)的顏色
document.vlinkColor //已點擊過的連結顏色
document.URL //設定URL屬性從而在同一視窗開啟另一網頁
document.fileCreatedDate //檔案建立日期,唯讀屬性
document.fileModifiedDate //檔案修改日期,唯讀屬性
document.fileSize //檔案大小,唯讀屬性
document.cookie //設定和讀出cookie
document.charset //設定字元集 簡體中文:gb2312
document:方法
document.write() //動態向頁面寫入內容
document_createElement_x_x_x(Tag) //建立一個html標籤對象
document.getElementByIdx_xx_x_x(ID) //獲得指定ID值的對象
document.getElementsByName(Name) //獲得指定Name值的對象
document.body.a(oTag)
body:子物件
document.body //指定文檔主體的開始和結束等價於


document.body.bgColor //設定或擷取對象後面的背景顏色
document.body.link //未點擊過的連結顏色
document.body.alink //啟用連結(焦點在此連結上)的顏色
document.body.vlink //已點擊過的連結顏色
document.body.text //文本色
document.body.innerText //設定…之間的文本
document.body.innerHTML //設定…之間的HTML代碼
document.body.topMargin //頁面上邊距
document.body.leftMargin //頁面左邊距
document.body.rightMargin //頁面右邊距
document.body.bottomMargin //頁面下邊距
document.body.background //背景圖片
document.body.a(oTag) //動態產生一個HTML對象

location:子物件
document.location.hash // #號後的部分
document.location.host // 網域名稱+連接埠號碼
document.location.hostname // 網域名稱
document.location.href // 完整URL
document.location.pathname // 目錄部分
document.location.port // 連接埠號碼
document.location.protocol // 網路通訊協定(http:)
document.location.search // ?號後的部分
常用對象事件:
documeny.location.reload() //重新整理網頁
document.location.reload(URL) //開啟新的網頁
document.location.assign(URL) //開啟新的網頁
document.location.replace(URL) //開啟新的網頁
selection-選區子物件
document.selection

Ios開發之 -- js和ios的互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.