iOS development--Interaction between JS and iOS

Source: Internet
Author: User

==webviewjavascriptbridge's Introduction = =


#下载: Https://github.com/marcuswestin/WebViewJavascriptBridge
#关于WebViewJavascriptBridge的介绍: http://blog.csdn.net/yanghua_kobe/article/details/8209751
==webviewjavascriptbridge (in conjunction with existing business code) small problem = =
*demo section (line 50th in the Exampleapp.html interface):

Bridge.callhandler (' Testobjccallback ', {' foo ': ' Bar '}, function (response) {


Since the underlying backhaul is two parameters Responsecallback (Message.error, message.responsedata), reponse corresponds to Message.error, This demo is undefinded;


* Source Implementation section (WebView load Callback event 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 the use of the process to set the WebView delegate first to itself, which is a must condition,
If you need to use WebView's callback event in your existing business code, you need to develop the business code itself as a follow-up delegate when initializing Webviewjavascriptbridge;
After setting the following delegate, problems will occur;


The above code causes Webviewdidfinishload to be called two times: WebView callback events are set in the business code. And the above code introduced in the. Js.txt resource, the resource has a direct modification of the DOM, will also trigger the webviewdidfinishload callback function;
This causes the webviewdidfinishload in the business code to be executed two times, resulting in errors or unnecessary calls;


Processing: No subsequent code processing is performed until the Js.txt resource is introduced, which prevents subsequent calls to the first viewdidload, as follows:


-(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 for the change of the source code, before the Js.txt load, for business follow-up call, not processing;
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];
}
}
}

* Source part (initialization function): nil cannot be used as the value of nsdictionary;

Error:
-(void) Callhandler: (NSString *) HandlerName {
[Self callhandler:handlername data:nil responsecallback:nil];
}
That's right:
-(void) Callhandler: (NSString *) HandlerName {
[self callhandler:handlername data:[nsnull null] responsecallback:nil];
}



Use = = of ==webviewjavascriptbridge
Direct code implementation of ===JS and iOS interaction = = =
*jos for JS calls:

[Self.paperquestionsshowwebview stringbyevaluatingjavascriptfromstring:[nsstring stringWithFormat:@] Setquestioncontent ('%@ ') ", Qtitle];

*js calls to iOS:

Change the href of the current window in the HTML JS code;


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


The above event triggers the callback event of the 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) {
Get user-selected options
NSString *usernewchoice = [RelativePath substringfromindex:doingrange.location+doingrange.length];
Update option content to server side
Determine if the current option is consistent with the submission to the server side, and if not, commit to the server-side
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 and iOS Interactive (webviewjavascriptbridge) code implementation = = =
Implementation of the *ios end:

Introduce header file:
#import "WebViewJavascriptBridge.h";


Specify the Webviewjavascriptbridge property:
@property (Strong, nonatomic) Webviewjavascriptbridge *javascriptbridge;


Initialize the Webviewjavascriptbridge;
_javascriptbridge = [Webviewjavascriptbridge bridgeforwebview:_paperquestionsshowwebview webViewDelegate:self Handler:nil];


Registration function;
[_javascriptbridge registerhandler:@ "Setsubjectivequestionscore" handler:^ (ID data, wvjbresponse *response) {
Get user-selected options
Nsinteger Userscorechoice = [(NSString *) data integervalue];
Update option content to server side
Determine if the current option is consistent with the submission to the server side, and if not, commit to the server-side

If you select a new score, sync to the server side
if (Userscorechoice!=self.currentquestionscore) {
[Self.delegate updateQuestionUserChooseScoreWithPid:self.paperId QuestionSequence:self.currentQuestionSequence Score:userscorechoice Sender:self];
}
}];


Call JS Code;
[_javascriptbridge callhandler:@ "Setrightanswer" data:qanswer];


Implementation of *JS:

Necessary Event registration and initialization:
Document.addeventlistener (' Webviewjavascriptbridgeready ', Onbridgeready, false);
function Onbridgeready (event) {
var bridge = Event.bridge;
Call the initialization function, cancel the queue, so that the message can be processed directly;
Bridge.init (function (message) {
alert (message);
});
}


Registration function:
function Onbridgeready (event) {
......
Bridge.registerhandler (' Setquestioncontent ', function (content) {


var e_content = document.getelementbyidx_x (' qcontent ');
E_content.innerhtml= content;

});
}


Implementation of JS on iOS call:
Newchoiceelement.onclick = function () {
Bridge.callhandler (' Choose ', this.value);
}



===js and iOS Interactive (Webviewjavascriptbridge) code implementation issues to be aware of = = =
#ios端必须保障框架中ios的实现作为webview的delegate, while the business code is added as a follow-up delegate processing in the initialization, otherwise the message is not delivered (it joins a queue but does not trigger the message delivery);
#js端必须实现init函数, otherwise the message is not delivered (a queue is added, but message delivery is not triggered);
#关于参数 (iOS): A single object can be passed directly (the underlying type such as int needs to be converted to the corresponding object); Multi-value transfer needs to be composed of nsdictionary for transmission;
#关于参数 (JS side): Single object directly passed; multi-valued composition JSON format string {' AA ': ' ss ', ' SDD ': ' RRR '};
#js语法以及编辑器对于错误的指示不明显, resulting in some character or punctuation errors, as well as the syntax is not complete errors are difficult to find, is a long time consuming place, need to find a more perfect JS editor to solve;


= = = Code introduces Webviewjavascriptbridge to realize the benefits of iOS and js interactions = = =
#协议: The realization of their own, in the communication part of the need to build a delivery protocol, many people realize the construction of the delivery protocol is different, more easily chaotic, the use of a unified framework, can reduce the problem;
#传递对象的字符转义: The framework handles this block again without having to transfer some of the characters themselves;
#框架封装了js和ios的多次交互, in the implementation of more complex interaction is useful, this block if the developers themselves, the code quality is difficult to control, and there is a certain amount of work;

Document: Properties

Document.title//Set document title equivalent to HTML
Document.bgcolor//Setting page background color
Document.fgcolor//setting foreground color (text color)
Document.linkcolor//Not clicked link color
Document.alinkcolor//Activate link (focus on this link) color
document.vlinkcolor//clicked link color
Document. URL//Set URL property to open another page in the same window
Document.filecreateddate//File build date, read-only property
Document.filemodifieddate//file modified date, read-only property
Document.filesize//File size, read-only properties
Document.cookie//settings and read-out cookie
Document.charset//setting Character Set Simplified Chinese: gb2312
Document: Method
document.write ()//write content dynamically to page
Document_createelement_x_x_x (TAG)//Create an HTML tag object
document.getelementbyidx_xx_x_x (ID)//Gets the object with the specified ID value
Document.getelementsbyname (name)//Gets the object of the specified Name value
DOCUMENT.BODY.A (Otag)
Body: child object
Document.body//Specifies that the beginning and end of the document body is equivalent to the


Document.body.bgColor//Sets or gets the background color behind the object
Document.body.link//non-clicked link color
Document.body.alink//Activation link ( The color of the focus on this link)
Document.body.vlink//clicked link color
Document.body.text//Text color
Document.body.innerText//settings ... Text between
Document.body.innerHTML//settings ... HTML code between
Document.body.topMargin//page top margin
Document.body.leftMargin//page left margin
Document.body.rightMargin// Page right margin
Document.body.bottomMargin//page bottom margin
document.body.background//Background picture
Document.body.a (otag)// Dynamically generates an HTML object

Location: Sub-object
Document.location.hash//#号后的部分
Document.location.host//domain + port number
Document.location.hostname//Domain name
Document.location.href//Full URL
Document.location.pathname//directory section
Document.location.port//Port number
Document.location.protocol//Network Protocol (http:)
Section after Document.location.search//?
Common Object events:
Documeny.location.reload ()//Refresh Web page
Document.location.reload (URL)//Open a new page
Document.location.assign (URL)//Open a new page
Document.location.replace (URL)//Open a new page
selection-Selection Sub-object
Document.selection

iOS development--Interaction between JS and iOS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.