从UIWebView中的javascript发送通知到ObjectiveC

mkt*_*kto 23 javascript objective-c ios

我需要知道如何在HTML中使用JavaScript UIWebView来通知Objective-C发生了什么事情?

更确切地说,我正在用HTML播放一些JavaScript动画,我需要提醒动画结束的Objective-C代码.

Cou*_*sen 46

似乎没有官方方法可以做到这一点.然而, 标准的 解决方法包括读取和解析传入的URL请求,基本上滚动你自己的序列化的消息传递协议.消息处理应该在webView:shouldStartLoadWithRequest:navigationType视图控制器的方法中完成.

注意:有几个免费库(PhoneGap,QuickConnect,JS-to-Cocoa Bridge)包含此功能(另外还有更多功能).要重新发明轮子(或者知道为什么它是圆的,可以这么说),请继续阅读.

在JavaScript中,您将通过尝试导航到新URL来调用回调:

// In JavaScript
window.location = 'myapp:myaction:param1:param2'; // etc...
Run Code Online (Sandbox Code Playgroud)

在Objective-C中,UIWebViewDelegate在您的.h文件中实现协议:

// In your header file
@interface MyAppViewController : UIViewController <UIWebViewDelegate> {
  ...
}
@end
Run Code Online (Sandbox Code Playgroud)

接下来,在您的.m文件中实现该方法:

// In your implementation file
-(BOOL)webView:(UIWebView *)webView2
       shouldStartLoadWithRequest:(NSURLRequest *)request
       navigationType:(UIWebViewNavigationType)navigationType
{
  // Break apart request URL
  NSString *requestString = [[request URL] absoluteString];
  NSArray *components = [requestString componentsSeparatedByString:@":"];

  // Check for your protocol
  if ([components count] > 1 &&
      [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"])
  {
    // Look for specific actions
    if ([(NSString *)[components objectAtIndex:1] isEqualToString:@"myaction"])
    {
      // Your parameters can be found at
      //   [components objectAtIndex:n]
      // where 'n' is the ordinal position of the colon-delimited parameter
    }

    // Return 'NO' to prevent navigation
    return NO;
  }

  // Return 'YES', navigate to requested URL as normal
  return YES;
}
Run Code Online (Sandbox Code Playgroud)

两个重要说明:

  1. 上下文:myapp:whatever在任何其他上下文中导航到(当然)失败.如果您正在加载跨平台页面,请记住这一点.

  2. 时间:如果window.location =在第一次返回之前进行第二次调用,它将"丢失".因此,要么将调用集中在一起,要么手动延迟执行,要么实现将上述内容与JS查询结合到Objective-C对象中的队列.