如何从Javascript调用Objective-C?

Obl*_*iux 41 iphone cocoa-touch uiwebview

我有一个WebView,我想从JavaScript调用Objective-C中的一个视图.有人知道我怎么做吗?


我的ViewController中有这个代码:

- (BOOL)webView:(UIWebView *)webView2 
 shouldStartLoadWithRequest:(NSURLRequest *)request 
 navigationType:(UIWebViewNavigationType)navigationType {

 NSString *requestString = [[request URL] absoluteString];
 NSArray *components = [requestString componentsSeparatedByString:@":"];

 if ([components count] > 1 && 
  [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
  if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) 
  {

   NSLog([components objectAtIndex:2]); [[Airship shared] displayStoreFront]; //<- This is the code to open the Store
   NSLog([components objectAtIndex:3]); // param2
   // Call your method in Objective-C method using the above...
  }
  return NO;
 }

 return YES; // Return YES to make sure regular navigation works as expected.
}
Run Code Online (Sandbox Code Playgroud)

并在Javascript中:

function store(event)
{
    document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;
}
Run Code Online (Sandbox Code Playgroud)

但没有任何反应.

Six*_*tto 52

标准的解决方法UIWebView是设置a UIWebViewDelegate并实现该方法webView:shouldStartLoadWithRequest:navigationType:.在您的JavaScript代码中,导航到一些伪造的URL,该URL会对您要传递给应用的信息进行编码,例如:

window.location = "fake://myApp/something_happened:param1:param2:param3";
Run Code Online (Sandbox Code Playgroud)

在您的委托方法中,查找这些虚假URL,提取您需要的信息,采取适当的操作,然后返回NO取消导航.如果你推迟使用某种味道的performSelector任何冗长的处理,这可能是最好.

  • 我建议[将您在URL中传递的数据序列化为JSON](http://stackoverflow.com/a/9827105/168594),它使事情变得更加灵活. (4认同)

tal*_*kol 32

不建议从JS调用目标c的window.location方法.问题的一个例子:如果你进行两次立即连续调用,则忽略一次(因为你不能太快地改变位置) - 自己尝试一下..

我推荐以下替代方法:

function execute(url) 
{
  var iframe = document.createElement("IFRAME");
  iframe.setAttribute("src", url);
  document.documentElement.appendChild(iframe);
  iframe.parentNode.removeChild(iframe);
  iframe = null;
}
Run Code Online (Sandbox Code Playgroud)

execute重复调用该函数,并且由于每个调用都在其自己的iframe中执行,因此在快速调用时不应忽略它们.

这个家伙的功劳.


Nos*_*dna 1

假设您正在开发一个应用程序,您可以查看PhoneGap如何实现它(甚至使用它)。它是一个支持 JS 和 OBJ-C 之间来回通信的库。还有其他库和解决方案。

如果您谈论的是 Web 应用程序(用户从 Mobile Safari 访问的东西),则无法从那里访问 Objective-C。