作为我正在开发的应用程序的一部分,用户需要能够从各种位置导入图像,包括从Web下载它们。我添加了一个应用内浏览器,并添加了一个上下文相关菜单,以便在用户长按特定项目时向用户显示不同的选项。
我的代码使用Javascript来检测HTML元素的标签,并基于以下教程和SO帖子:
http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/
UIWebView - Enabling Action Sheets on <img> tags
UILongPressGestureRecognizer调用以下方法:
(void)openContextMenuAt:(CGPoint)pt
{
// Load the JavaScript code from the Resources and inject it into the web page
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSTools" ofType:@"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self.webView stringByEvaluatingJavaScriptFromString: jsCode];
// get the Tags and URL at the touch location
NSString *tags = [self.webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];
NSString *elementURL = [self.webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"MyAppGetLinkHREFAtPoint(%i,%i);", (NSInteger)pt.x, (NSInteger)pt.y]];
// create the UIActionSheet and populate it with buttons related to the tags
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:elementURL
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
BOOL shouldShowMenu = NO;
// If a link was touched, add link-related buttons
if ([tags rangeOfString:@",A,"].location != NSNotFound) {
[sheet addButtonWithTitle:NSLocalizedString(@"Open", nil)];
shouldShowMenu = YES;
}
// If an image was touched, add image-related buttons
if ([tags rangeOfString:@",IMG,"].location != NSNotFound) {
[sheet addButtonWithTitle:NSLocalizedString(@"Save Image", nil)];
shouldShowMenu = YES;
}
// check the item to see if it has an audio link attached
NSSet *validAudioExtensions = [NSSet setWithObjects:@"aiff", @"aac", @"alac", @"m4a", @"mp3", @"raw", @"wav", nil];
NSString *urlSuffix = [[elementURL pathExtension] lowercaseString];
if ([validAudioExtensions containsObject:urlSuffix]) {
[sheet addButtonWithTitle:@"Save Audio"];
shouldShowMenu = YES;
}
// Add buttons which should be always available
[sheet addButtonWithTitle:NSLocalizedString(@"Open in Safari", nil)];
if (shouldShowMenu == YES)
{
CGRect menuTarget = CGRectMake(pt.x, pt.y, 1, 1);
[sheet setActionSheetStyle:UIActionSheetStyleBlackOpaque];
[sheet showFromRect:menuTarget inView:self.webView animated:YES];
}
}
直到最近,这几乎在我测试的每个网站上都能很好地运行。然而,它已经停止了谷歌的图像搜索工作(不幸的是,这是大多数用户可能会看到的第一个地方)。
在主搜索结果(带图像缩略图)上,我能够检测到IMG标签并下载缩略图图像。但是,如果我点击缩略图以显示较大的全尺寸图像,我将无法再检测到我正在按下的内容。此外,我无法从任一视图中检索URL(打印网址只显示一个空字符串)。
是否有另一种更好的方法来检测哪个元素被按下了?我需要为Google使用特定的解决方法吗?
提前感谢您的帮助。