Reputation: 685
In my app, I have a webview, and wanted to open images loaded in a webpage in a separate view controller, which is fine, all I need to do is get the URL to the source of the image & load it in a different view controller, which I can do.
Here is the code I'm using to get the URL to the source of the image.
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
CGPoint touchPoint = [touch locationInView:self.view];
NSString *imageSRC = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSString *srcOfImage = [webView stringByEvaluatingJavaScriptFromString:imageSRC];
NSLog(@"src:%@",srcOfImage);
}
return YES;
}
Now, my question is, sometimes, when an image might have a link (i.e. tag) with it, the webview will load the link while the image opens in my separate view controller. What I would like to do is, stop the webview from opening the link (only the ones in the images) if one exists. Any pointers to how I may go about accomplishing that?
Upvotes: 2
Views: 2006
Reputation: 685
Finally figured it out, the answer lied in UIWebViewDelegate. For anyone who's interested, here's how I solved it..
bool isImage;
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
CGPoint touchPoint = [touch locationInView:self.view];
NSString *imageSRC = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSString *srcOfImage = [webView stringByEvaluatingJavaScriptFromString:imageSRC];
NSLog(@"src:%@",srcOfImage);
NSURL *imgsrcURL = [NSURL URLWithString:srcOfImage];
if (imgsrcURL && imgsrcURL.scheme && imgsrcURL.host) {
isImage = TRUE;
}
}
return YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ((navigationType == UIWebViewNavigationTypeLinkClicked) && (isImage)) {
return NO;
isImage = FALSE;
} else {
return YES;
}
}
Upvotes: 3