Objective-C and JS call each other and PASS Parameters note

Source: Internet
Author: User

1. Objective-C calls the js method. You only need to call the method that comes with uiwebview.

 
[Webview stringbyevaluatingjavascriptfromstring: [nsstring stringwithformat: @ "gethtmlstring ('% @')", htmlstr];

2. When JS calls the objective-C method, a parameter or method needs to be agreed with Js.

 
-(Bool) webview :( uiwebview *) webview shouldstartloadwithrequest :( nsurlrequest *) Request navigationtype :( uiwebviewnavigationtype) navigationtype

In this callback method, we will get the data request sent from the server. We can determine the passed parameters and then determine the method for calling oC.

If ([request. URL. scheme isequaltostring: @ "gethtmlstring"]) {nsstring * htmlstr = [self gethtmlstring: description]; htmlstr = [htmlstr encoding: nsutf8stringencoding]; [webview encoding: [nsstring stringwithformat: @ "gethtmlstring (\" % @ \ ")", htmlstr];}

In this way, the OC is called.

Here is a particularly noteworthy question: I have uploaded parameters in HTML format. I have encountered it here. The parameters passed in are always incorrect and cannot call JS methods.

Stringwithcontentsoffile, which is used to read files. If no encoding method is specified, data may be lost. Therefore, we have specified the UTF-8 encoding method. There is another possible problem when passing parameters. If this parameter contains (\ r \ n') and so on, the JS side cannot receive this value, and these with \ needs to be escaped. The following code writes JavaScript to receive the complete message:

 
Message = [Message stringbyreplacingoccurrencesofstring: @ "\ n" withstring: @ "\\\\ N"]; nsstring * jsmethod = [nsstring stringwithformat: @ "jsmethod (\" % @ \ ")", message]

ExampleCode: Http://download.csdn.net/detail/pearlhuzhu/5550141

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.