//长按手势
UILongPressGestureRecognizer * longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
longPressed.delegate = self;
[self.webView addGestureRecognizer:longPressed];
(void)longPressed:(UITapGestureRecognizer*)recognizer{
//只在长按手势开始的时候才去获取图片的url
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [recognizer locationInView:self.webView];
NSString *js = [NSString stringWithFormat:@”document.elementFromPoint(%f, %f).src”, touchPoint.x, touchPoint.y];
self.urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:js];
if (self.urlToSave.length == 0) {
return;
}UIActionSheet* sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@”取消” destructiveButtonTitle:nil otherButtonTitles:@”保存图片”, nil];
sheet.cancelButtonIndex = sheet.numberOfButtons - 1;
[sheet showInView:[UIApplication sharedApplication].keyWindow];
// NSLog(@”获取到图片地址:%@”,self.urlToSave);
}
(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (actionSheet.numberOfButtons - 1 == buttonIndex) {
return;
}
NSString* title = [actionSheet buttonTitleAtIndex:buttonIndex];
if ([title isEqualToString:@”保存图片”]) {NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.urlToSave]];
UIImage* image = [UIImage imageWithData:data];//UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);}
}
(void)image:(UIImage )image didFinishSavingWithError:(NSError)error contextInfo:(void*)contextInfo
{
if (error){NSLog(@"Error"); }else { //弹出动画提示取消收藏成功 self.tip.image = [UIImage imageNamed:@"Collect.png"]; [UIView animateWithDuration:1 animations:^{ self.tip.alpha = 1.0f; self.tip.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 3 - 5 * ScreenWidth, 160 * ScreenHeigth - 5 * ScreenHeigth, [UIScreen mainScreen].bounds.size.width / 3 + 10 * ScreenWidth, 130 * ScreenHeigth); [self.view addSubview:self.tip]; } completion:^(BOOL finished) { self.tip.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 3, 160 * ScreenHeigth, [UIScreen mainScreen].bounds.size.width / 3, 120 * ScreenHeigth); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [UIView animateWithDuration:0.2 animations:^{ self.tip.alpha = 0.f; }]; }); }]; NSLog(@"OK"); }
}
//可以识别多个手势
-(BOOL)gestureRecognizer:(UIGestureRecognizer )gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer )otherGestureRecognizer
{
return YES;
}