从UIWebView传递警报到iOS应用程序

时间:2015-11-15 22:33:58

标签: javascript objective-c

我创建了一个应用程序,工作正常。我唯一需要的是将警报从uiwebview传递到我的iOS应用程序。

我的uiwebview上有此提醒

<div id="alerts" class="alerts">

<p class="alert-red">ok. come back again tomorrow, not now.</p>

我想将此提醒转移到我的应用中并将其转换为uialertview

UIAlertView *errr = [[UIAlertView alloc]initWithTitle:@"nil" message:@"ok. come back again tomorrow, not now." delegate:self cancelButtonTitle:@"Ok, Got it" otherButtonTitles:nil, nil];
    [errr show];

任何想法如何实现这个结果?当这个警告出现在uiwebview上时,我需要NSNotification来收听吗?

我试过这样的事情

NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"var targetDiv = document.getElementById('alerts').getElementsByClassName('alert-red')[0];"];

NSLog(@"%@",theTitle);

所以我可以尝试从“alert-red”中检索该消息,但不起作用。

我是javascript和html的新手

1 个答案:

答案 0 :(得分:0)

This is the typical workaround用于解决此问题:

在您的网页中,当您想要显示此提醒时,请运行此javascript代码:

window.location = 'custom_action';

然后在控制器上的objc实现shouldStartLoadWithRequest(并设置yourWebView.delegate = yourController

-(BOOL)webView:(UIWebView *)webView
       shouldStartLoadWithRequest:(NSURLRequest *)request
       navigationType:(UIWebViewNavigationType)navigationType {
  // detect when the webview switches to this custom url
  if([[[request URL] absoluteString] isEqualToString: @"custom_action"]) {
    UIAlertView *errr = [[UIAlertView alloc]initWithTitle:@"nil" message:@"ok. come back again tomorrow, not now." delegate:self cancelButtonTitle:@"Ok, Got it" otherButtonTitles:nil, nil];
    [errr show];
    // this prevents the webview from actually trying to load the custom url
    return NO;
  }
  // allow the url to load if its not your custom url
  return YES;
}