天天看点

Ios开发之 -- js和ios的交互

==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的后续调用,修改后如下:

    //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];

正确:

    [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;

        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);

                            });

   }

  注册函数:

             ......

                 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

上一篇: js

继续阅读