Original source: http://mkhgg.blog.51cto.com/1741572/752962
The interaction between JS and Objective-c in iOS
Because there is no webkit.framework this library in iOS, there is no Windowscriptobject object method. If there's a way to do this,
More convenient, (Ps:macos) Now we use other methods to achieve JS and objective-c interactive effect. The first is the OBJECTIVE-C call JS code, you can use a method in the UIWebView
Stringbyevaluatingjavascriptfromstring: The method name is followed by JS. The return value of this function is the return value of the called JS method. And in the JS call objective-c method is not so simple, in the JS code should do this:
1 function 23 alert (14 5 document.location= "objc://" +cmd+ ":/" +PARAMETER1; // 6
And in Objective-c, it is also a method of using UIWebView,
1-(BOOL) WebView: (uiwebview*) WebView shouldstartloadwithrequest:2(nsurlrequest*) Request Navigationtype:3(Uiwebviewnavigationtype) Navigationtype//This method is triggered by every request in the Web page .4 { 5NSString *urlstring =[[Request URL] absolutestring];6Nsarray *urlcomps =[URLString7Componentsseparatedbystring:@"://"]; 8 if([Urlcomps Count] && [[Urlcomps Objectatindex:0] 9Isequaltostring:@"OBJC"]) Ten { OneNsarray *arrfucnameandparameter = [(nsstring*) [Urlcomps
AObjectatindex:1] Componentsseparatedbystring:@":/"]; -NSString *funcstr = [Arrfucnameandparameter objectatindex:0]; - if(1==[Arrfucnameandparameter Count]) the { - //No Parameters - if([Funcstr isequaltostring:@"doFunc1"]) - { + /*calling local function 1*/ -NSLog (@"doFunc1"); + } A } at Else if(2==[Arrfucnameandparameter Count]) - { - //with parameters. - if([Funcstr isequaltostring:@"doFunc1"] && -[Arrfucnameandparameter Objectatindex:1]) - { in /*calling local function 1*/ -NSLog (@"Dofunc1:parameter"); to } + } - returnNO; the }; * returnYES; $}
This method can achieve JS call local Objective-c method, unfortunately there is no way to return the value to JS, so still want to bypass
Stringbyevaluatingjavascriptfromstring: This bend, with
Stringbyevaluatingjavascriptfromstring:
function to remove the JS method, the return value as a parameter in the JS method to pass back to
Js. This can have, hehe ~
This article is from the "commiseration" blog, make sure to keep this source http://mkhgg.blog.51cto.com/1741572/752962
Reprint: Objective-c and JS Interaction in iOS