步驟:
1嗦嗡、創(chuàng)建手勢(shì)
2勋锤、監(jiān)聽(tīng)手勢(shì),獲取到點(diǎn)擊的point
3侥祭、根據(jù)webview js代碼:Document.elementFromPoint(x,y).src 拿到image的src標(biāo)簽叁执,并且通過(guò)stringByEvaluatingJavaScriptFromString轉(zhuǎn)換為url的字符串
4茄厘、給url做非空判斷,有值時(shí) 彈出提示框,然后下載圖片徒恋,通過(guò)UIImageWriteToSavedPhotosAlbum保存到相冊(cè)
關(guān)鍵代碼:一蚕断、
- (void)longPress:(UILongPressGestureRecognizer*)longPressGestureRecognizer{
if(longPressGestureRecognizer.state!=UIGestureRecognizerStateBegan){
return;
}
CGPointtouchPoint = [longPressGestureRecognizerlocationInView:self.webView];
NSString*srcStr = [NSStringstringWithFormat:@"document.elementFromPoint(%f, %f).src",touchPoint.x,touchPoint.y];
NSString*saveUrl = [self.webViewstringByEvaluatingJavaScriptFromString:srcStr];
if(srcStr.length==0){
return;
}
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"保存圖片到相冊(cè)"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction*okAction = [UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
[selfsavePhotoToPhotosAlbumWithImgUrl:saveUrl];
}];
UIAlertAction*cancelAction = [UIAlertActionactionWithTitle:@"Cancel"style:UIAlertActionStyleCancelhandler:nil];
[alertaddAction:okAction];
[alertaddAction:cancelAction];
[selfpresentViewController:alertanimated:YEScompletion:nil];
}
- (void)savePhotoToPhotosAlbumWithImgUrl:(NSString*)url {
NSURL*ImgUrl = [NSURLURLWithString:url];
NSURLSessionConfiguration*configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSession*session = [NSURLSessionsessionWithConfiguration:configurationdelegate:selfdelegateQueue:[NSOperationQueuenew]];
NSURLRequest*request = [NSURLRequestrequestWithURL:ImgUrlcachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:30.0];
NSURLSessionDownloadTask*task = [sessiondownloadTaskWithRequest:requestcompletionHandler:^(NSURL*_Nullablelocation,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) {
if(error){
return;
}
NSData*imgData = [NSDatadataWithContentsOfURL:location];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage*img = [UIImageimageWithData:imgData];
UIImageWriteToSavedPhotosAlbum(img, self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
});
}];
[taskresume];
}