如何从Javascript调用Object-C?

如何从Javascript调用Object-C?

我有一个WebView,我想从JavaScript调用Object-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.}

在Javascript中:

function store(event){
    document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;}

但什么都没发生。


紫衣仙女
浏览 627回答 3
3回答

慕虎7371278

标准的解决办法UIWebView是设置一个UIWebViewDelegate,并实现了该方法。webView:shouldStartLoadWithRequest:navigationType:..在JavaScript代码中,导航到某个伪URL,该URL编码要传递给应用程序的信息,例如:window.location&nbsp;=&nbsp;"fake://myApp/something_happened:param1:param2:param3";在委托方法中,查找这些假URL,提取所需的信息,采取任何适当的操作,然后返回。NO取消导航。使用一些味道.performSelector.

catspeake

不推荐从JS调用目标c的window.Location方法。问题的一个例子:如果你连续打了两个电话,其中一个被忽略了(因为你不能太快地改变位置)-你自己试试吧。我建议采取以下替代办法:function&nbsp;execute(url)&nbsp;{ &nbsp;&nbsp;var&nbsp;iframe&nbsp;=&nbsp;document.createElement("IFRAME"); &nbsp;&nbsp;iframe.setAttribute("src",&nbsp;url); &nbsp;&nbsp;document.documentElement.appendChild(iframe); &nbsp;&nbsp;iframe.parentNode.removeChild(iframe); &nbsp;&nbsp;iframe&nbsp;=&nbsp;null;}你打电话给execute函数,由于每个调用都在自己的iframe中执行,因此在快速调用时不应忽略它们。贷给这家伙.
打开App,查看更多内容
随时随地看视频慕课网APP