检测UIWebView内的tapped图像

时间:2014-09-18 16:55:09

标签: javascript html ios uiwebview uiwebviewdelegate

我有一个网页视图,显示其他人完成的html + js介绍。当用户点击特定图像时,我需要执行segue。我不知道javascript。 如果我尝试使用.src返回空,如果尝试.innerHTML总是返回很多代码。 如何检测这种特定的触摸?谢谢。

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    [tap setDelegate:self];
    [self.webView.scrollView addGestureRecognizer:tap];

    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"html" inDirectory:@"myDir"];
    NSURL* url = [[NSURL alloc]initFileURLWithPath:htmlFile];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}
-(void)viewTapped:(UITapGestureRecognizer*)tap {
    CGPoint touchPoint = [tap locationInView:self.webView];
    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:js];
//Returning an empty string
    if (urlToSave.length > 0) {
          [self performSegueWithIdentifier:@"introToMain" sender:self];
    }

}

1 个答案:

答案 0 :(得分:0)

我认为你应该在html中点击你的图像。如果是,请忽略这一点。 然后你应该使用UIWebView的shouldStartLoadWithRequest委托方法,如下所示:

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


    if (navigationType == UIWebViewNavigationTypeLinkClicked){

        NSURL *url = request.URL;
        //Maybe you can detect the image here looking to the url.

    }

    return YES;

}