为了实现 使用WebView展示的网页的时候 可以把网页上的所有的图片给提取出来 并且可以给WebView添加点击时间 当点击到图片的时候 可以获取出改图片的Url,下面是方法的介绍
1、首先到如第三方库 TFHpple
2、
//获取网页上全部的图片
-(void)dowmLoadPhoto{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (response == nil){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警告!" message:@"无法连接到该网站!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
[alertView show];
return;
}
NSArray *imagesData = [self parseData:response];
NSMutableArray *images = [self downLoadPicture:imagesData];
}
//解析html数据
- (NSArray*)parseData:(NSData*) data
{
TFHpple *doc = [[TFHpple alloc] initWithHTMLData:data];
//在页面中查找img标签
NSArray *images = [doc searchWithXPathQuery:@"//img"];
return images;
}
//下载图片的方法
- (NSMutableArray*)downLoadPicture:(NSArray *)images
{
//创建存放UIImage的数组
_downloadImages = [[NSMutableArray alloc] init];
_imageViewArr =[[NSMutableArray alloc]init];
for (int i = 0; i < [images count]; i++)
{
// 查看网页里面的img标签里面的关于图片url那个标签 可能是一般是src 所以下面就是[[[images objectAtIndex:i] objectForKey:@"src"] 如果是其他的就替换下就可以了
NSString *prefix = [[[images objectAtIndex:i] objectForKey:@"src"] substringToIndex:4];
NSString *url = [[images objectAtIndex:i] objectForKey:@"src"];
//判断图片的下载地址是相对路径还是绝对路径,如果是以http开头,则是绝对地址,否则是相对地址
if ([prefix isEqualToString:@"http"] == NO){
url = [path stringByAppendingPathComponent:url];
}
if(url != nil){
[_downloadImages addObject:url];
}
}
}
return _downloadImages;
}
//给webVeiw添加点击时间 回去点击位置的图片的Url
-(void)addTapOnWebView
{
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[_wv addGestureRecognizer:singleTap];
singleTap.delegate = self;
singleTap.cancelsTouchesInView = NO;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
//获取点击的图片
-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{
CGPoint pt = [sender locationInView:_wv];
NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];
NSString *urlToSave = [_wv stringByEvaluatingJavaScriptFromString:imgURL];
if([urlToSave hasPrefix:@"http"])
{
int index = [_downloadImages indexOfObject:urlToSave];
int count = _downloadImages.count;
// 1.封装图片数据
NSMutableArray *photos = [[NSMutableArray alloc]init];
NSMutableArray *_viewArr =[[NSMutableArray alloc]init];
for (int i = 0; i<count-1; i++) {
MJPhoto *photo = [[MJPhoto alloc] init];
photo.url = [NSURL URLWithString:[_downloadImages objectAtIndex:i]] ; // 图片路径
[photos addObject:photo];
}
}