In the development of UIWebView, JS and Oc,js interact with Swift, and the method of transferring parameters to each other

Source: Internet
Author: User

The actual development often encountered the need to pass parameters to the WebView or from the webview to take parameters, here wrote a super simple demo for everyone to reference, I JS just learned a day, so the shortcomings of the Haihan.

Nonsense not much to say directly on the code

OC version

1 #import "ViewController.h"2 @interfaceViewcontroller () <UIWebViewDelegate>3@property (nonatomic, strong) UIWebView *WebView;4 @end5 6 @implementationViewcontroller7 8- (void) Viewdidload {9 [Super Viewdidload];Ten     //additional setup after loading the view, typically from a nib. OneSelf.view.backgroundColor =[Uicolor Whitecolor]; ASelf.title =@"Web Test"; - [Self.view AddSubview:self.webView]; - } the  --(UIWebView *) webview{ -     if(!_webview) { -_webview =[[UIWebView alloc] Initwithframe:[uiscreen mainscreen].bounds]; +_webview.Delegate=Self ; -NSString *filepath = [[NSBundle mainbundle] Pathforresource:@"Test"OfType:@". html"]; +Nsurlrequest *request =[Nsurlrequest Requestwithurl:[nsurl Urlwithstring:filepath]; A [_webview loadrequest:request]; at     } -     return_webview; - } -  --(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (Nsurlrequest *Request Navigationtype: (uiwebviewnavigationtype) navigationtype{ -      in     if([Request. Url.absolutestring Hassuffix:@"clickloginbtn"]) { - //passing data to JS to[_webview stringbyevaluatingjavascriptfromstring:[nsstring stringWithFormat:@"Logincallback (' I am ID from app ', ' I am tokens from app ')"]]; + //get data from JS -NSString *webdata = [_webview stringbyevaluatingjavascriptfromstring:@"returndata ();"]; theNSLog (@"%@", WebData); *          $ [_webview stoploading];Panax Notoginseng     } -     returnYES; the}

The main method is to execute in WebView agent: stringbyevaluatingjavascriptfromstring:@ "JS Method Name" method, you can invoke JS function in the Web

1<! DOCTYPE html>23     45         6<script>7             functionLogincallback (id,token) {8                 varX=document.getelementbyid ("Logindata");
Ten alert (ID) One alert (token) A } -</script> - the - -<body> -&LT;H2 id= "Logindata" align= center>clict to transmit data +<button id= "Hello" onclick= "ButtonClick ()" >login</button> -<script > + functionButtonClick () A {
WebView Redirection atdocument.location = "Clickloginbtn" - } - functionReturndata () { - returndocument.getElementById ("Logindata"). Script - } -</script> in</body> -

The function functions written in <script></script> will be called by the above method of OC, then the parameters of OC and JS can be passed by the type of the function, passing in parameters and outgoing parameters.

Note that when you click a button on the Web, the ButtonClick method is executed, but if you do not redirect the Web page, no new request requests are sent, no proxy methods are executed in WebView, the proxy method is not executed, and the execution of the proxy method is a precondition for passing parameters. So be sure not to forget to redirect the WebView.

Swift version

The basic principle of these, the following is attached to the interaction between Swift and JS, the principle is interlinked

Swift Code

1 Import UIKit2 classViewcontroller:uiviewcontroller, uiwebviewdelegate{3 4     Overridefunc viewdidload () {5 super.viewdidload ()6         //additional setup after loading the view, typically from a nib.7         8Self.title ="Web-js Test"9Self.view.backgroundColor =Uicolor.bluecolor ()Ten          OneLet filepath:string = Nsbundle.mainbundle (). Pathforresource ("Test", OfType:". html")! ALet request =Nsurlrequest.init (Url:nsurl (fileurlwithpath:filepath)) -          -Let WebView =Uiwebview.init (Frame:UIScreen.mainScreen (). Bounds) theWebView.Delegate=Self ; - Self.view.addSubview (WebView) -          - webview.loadrequest (Request) +  -     } +Func WebView (Webview:uiwebview, Shouldstartloadwithrequest request:nsurlrequest, Navigationtype: Uiwebviewnavigationtype)Bool { A         //Core Code at         ifRequest. Url!. Absolutestring.hassuffix ("URL"){ -LetID="' I am ID from app '" -Let Tocken ="' I am tocken from app '" - //passing parameters to H5 -Webview.stringbyevaluatingjavascriptfromstring ("Senddatatoweb (\ (id), \ (Tocken))") - //receive parameters from H5 inLet Returnstr = webview.stringbyevaluatingjavascriptfromstring ("Getdatafromweb ()") - print (RETURNSTR) to webview.stoploading () +         } -         return true the}

JS Code

1<! DOCTYPE html>23<body>4&LT;H2 align=center id= "Logindata" >click to transmit data5<button id= "Hallo" onclick= "ButtonClick ()" Align=center>login</button>6<script>7             functionButtonClick ()8             {9                 //Heavy PointingTendocument.location = "url" One             } A          -             functionSenddatatoweb (id,token) { - alert (ID) the alert (token) -document.getElementById ("Logindata"). InnerHTML = "Data transmit complete" -             } -          +             functionGetdatafromweb () { -                 return"I am a string from the Web" +             } A          at</script> -  -  -</body> -

There is also a way for JavaScript to invoke the OC code directly instead of changing the URL callback method by invoking the JS function directly by not executing the WebView proxy, via <javascriptcore/javascriptcore.h > Framework to achieve, the actual measurement is effective. However, the method is not very familiar with this method is not chosen to do, also recommended.

UIWebView in development, JS and Oc,js interact with swift, passing parameters to each other method

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.