If there is only one webview for JS to communicate with iOS local code can use the off-the-shelf phonegap framework, now that the project requires the development of the ipad version of the application, the page has more than multiple webview need to write their own JS code to implement JS and local code communication.
The basic principle is: WebView Access special URL prefix address, and then in the Uiwebviewdelegate Shouldstartloadwithrequest method to filter the URL can be reached JS and local code to communicate.
1. Implement the Uiwebviewdelegate in Mainviewcontroller and implement the Shouldstartloadwithrequest method:
<p class= "P1" > #define callfunction_prefix @<span class= "S1" > "callfunction://" </span></p>
-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) navigationtype{ [[UIApplication sharedapplication] SendAction: @selector ( Resignfirstresponder) To:nil From:nil Forevent:nil]; NSString *url = [Request. URL absolutestring]; NSLog (@ "Should url =%@ Webview.tag =%d", url,webview.tag); if ([url hasprefix:@ "/http"] | | [url hasprefix:@ "https://"]) { return [self Logoutwithalertwebview:webview url:url]; } else if ([url Hasprefix:callfunction_prefix]) { NSLog (@ "Webview.tag =%d", webview.tag); [[Basicplugin Getinstance]executepluginbyurl:url Tag:webView.tag]; return NO; } return YES;}
2. The following code performs the specified method of the specified class by reflection of the class name and method name:
-(void) Executepluginbyurl: (nsstring *) URL tag: (nsinteger) tag{nsrange range = [url Rangeofstring:callfunction_prefix] ; NSString *temp = [url substringFromIndex:range.location + range.length]; Nsarray *arr = [Temp componentsseparatedbystring:@ "&"]; NSString *callbackid = @ ""; NSString *classname = @ ""; NSString *methodname = @ ""; Nsmutablearray *params = [Nsmutablearray arraywithcapacity:0]; if (arr! = nil && arr.count > 0) {nsstring *tt = [arr objectatindex:0]; Nsarray *temparr = [tt componentsseparatedbystring:@ "="]; Callbackid = [Temparr objectatindex:1]; tt = [arr objectatindex:1]; Temparr = [tt componentsseparatedbystring:@ "="]; ClassName = [Temparr objectatindex:1]; tt = [arr objectatindex:2]; Temparr = [tt componentsseparatedbystring:@ "="]; MethodName = [Temparr objectatindex:1]; tt = [arr objectatindex:3]; Temparr = [TT Componentsseparatedbystring:@ "="]; NSString *paramstr = [Temparr objectatindex:1]; PARAMSTR = [Paramstr stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding]; if (paramstr! = nil && paramstr.length > 0) {params = [Nsmutablearray arraywitharray:[paramstr compon entsseparatedbystring:@ "$"]; }//Reflection call has a parameter method nsmutablearray *pp = [Nsmutablearray arraywithcapacity:0]; [pp addobject:[nsstring stringwithformat:@ "%d", tag]]; [pp Addobject:callbackid]; For (NSString *t in params) {[pp addobject:t]; } Class cls = nsclassfromstring (className); ID a= [[CLS Alloc] init]; SEL selector = nsselectorfromstring ([nsstring stringwithformat:@ "%@%@", methodname,@ ":"]); if ([a respondstoselector:selector]) {@try {[a performselector:selector withobject:pp]; } @catch (NSException *exception) {NSLog (@ "Basicplugin:class:%@ ' s method:%@ is not found. ", Classname,methodname); } } }
3.js plug-in writing, using Location.href access to the specified URL, there is a bug is, cannot call two plug-ins at the same time, because the second plug-in Location.href will overwrite the first location.href, So you need to wait for the first execution to finish before you can execute the second one.
Define plug-in $ (function () {//var Js2native_exception_arr = ["Homeviewpluginshowmask", "Homeviewpluginunmask", " Homeviewpluginalert "]; function PageName () {var strurl=location.href; var arrurl=strurl.split ("/"); var strpage=arrurl[arrurl.length-1]; return strpage; } if (!window.plugins) {window.plugins = {}; } if (!window.js2native) {window.js2native = {exec:function (classname,methodname,params) {var arr = params; var arrstr = '; if (arr && arr.length > 0) {for (var tt in arr) {arrstr + = ' $ '; Arrstr + = Arr[tt]; } arrstr = arrstr.substring (1); } var url= "callfunction://callbackid=" + className + methodName + "event&classname=" +classname+ "&metho d= "+methodname +" ¶ms= "+ encodeuricomponent (ARRSTR); URL + = ("¤tpage=" + pageName ()); URL + = ("&tt=" + New Date (). GetTime ()); var temp = className + methodName; for (Var tt in Js2native_exception_arr) {var et = js2native_exception_arr[tt]; if (et = = temp) {url = "http://" + URL; $.get (URL); Return }} location.href = URL; } }; }//------------------------------plug-in method------------------------////1.infopluginfunction Infoplugin () {};/** * Get context Path */InfoPlugin.prototype.getCtx = function () {js2native.exec ("Infoplugin", "Getctx", []); }; Window.plugins.infoPlugin = new Infoplugin (); });
4. WhereJs2native_exception_arr is intended for asynchronous access to the backend and requiresNsurlcache used together.
@interface Localsubstitutioncache:nsurlcache<nsurlconnectiondatadelegate>{nsmutabledictionary * cachedresponses;} -(Nscachedurlresponse *) Cachedresponseforrequest: (Nsurlrequest *) request{////Get The path for the request//NSString *pathstring = [[Request URL] absolutestring]; NSString *relativepath=[[request URL] relativepath]; NSString *version = [[Request URL] query]; NSLog (@ "localsubstitutioncache===%@", pathstring); if (pathstring! = Nil &&![ @ "" isequaltostring:pathstring] && [pathstring Hasprefix:exception_callfunction_prefix]) {pathString = [path String substringfromindex:[exception_callfunction_prefix length]]; pathstring = [NSString stringwithformat:@ "%@%@", exception_callfunction_replace,pathstring]; [[Basicplugin getinstance]executepluginbyurl:pathstring tag:1]; NSLog (@ "Cachedresponseforrequest.executepluginbyurl =%@", pathstring); return [Super Cachedresponseforrequest:request]; }......
Notes on JS and local communication in iOS