为了账号安全,请及时绑定邮箱和手机立即绑定

如何从Javascript调用Object-C?

如何从Javascript调用Object-C?

紫衣仙女 2019-07-15 14:58:58
如何从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;}但什么都没发生。
查看完整描述

3 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

标准的解决办法UIWebView是设置一个UIWebViewDelegate,并实现了该方法。webView:shouldStartLoadWithRequest:navigationType:..在JavaScript代码中,导航到某个伪URL,该URL编码要传递给应用程序的信息,例如:

window.location = "fake://myApp/something_happened:param1:param2:param3";

在委托方法中,查找这些假URL,提取所需的信息,采取任何适当的操作,然后返回。NO取消导航。使用一些味道.performSelector.


查看完整回答
反对 回复 2019-07-15
?
catspeake

TA贡献1111条经验 获得超0个赞

不推荐从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;}

你打电话给execute函数,由于每个调用都在自己的iframe中执行,因此在快速调用时不应忽略它们。

贷给这家伙.


查看完整回答
反对 回复 2019-07-15
  • 3 回答
  • 0 关注
  • 622 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信