其实WkWebView是自带长按保存功能的,iOS12及以前的弹框会显示“存储图像”和“拷贝”,分别会保存到相册和拷贝到剪切板。
iOS13长按图片会有一个动态弹出的效果,然后会显示三个选项:共享、添加到照片、拷贝,其中添加到照片和拷贝都是可以正常使用的,但是共享就要看情况了:
1.当长按获取的页面元素是图片url链接时,是可以分享到微信的,但是会没有标题,没有缩略图,并且由于分享的是链接地址,所以还需要对方点开才能看到图片。
2.当长按获取的页面元素是编码后的data时,通过系统分享是分享不到微信的。
所以有必要自定义一套长按保存分享的流程了。
1.首先屏蔽掉webView自带的点击和长按事件
WKUserContentController* userContentController =WKUserContentController.new;
NSMutableString *javascript = [NSMutableString string]; [javascriptappendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按[javascriptappendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[userContentControlleraddUserScript:cookieScript];
2.给webView添加长按手势,只针对长按手势做处理
-(UILongPressGestureRecognizer *)mLongPressGes{
if (!_mLongPressGes) {
_mLongPressGes= [[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(startLongPress:)];
_mLongPressGes.delegate = self;
_mLongPressGes.minimumPressDuration = 0.4f; _mLongPressGes.numberOfTouchesRequired = 1; _mLongPressGes.cancelsTouchesInView = YES;
}
return _mLongPressGes;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
if ([otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {
return YES;
}else{
return NO;
}
}
3.针对图片链接和base64编码的data分别作出处理
- (void)startLongPress:(UIGestureRecognizer *)ges{
if (ges.state!=UIGestureRecognizerStateBegan) {
return;
}
CGPointtouchPoint = [geslocationInView:ges.view];
NSString *jsString = [NSString stringWithFormat:@"function getURLandRect(){\
var ele=document.elementFromPoint(%f, %f);\
var url=ele.src;\
var jsonString= `{\"url\":\"${url}\"}`;\
return(jsonString)} getURLandRect()", touchPoint.x, touchPoint.y];
@weakify(self);
[self.wk_mWebViewevaluateJavaScript:jsStringcompletionHandler:^(id_Nullableresult,NSError*_Nullableerror) {
@strongify(self);
NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary*resultDic = [NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];
NSString*imageURL = [NSStringisNullToString:resultDic[@"url"]];
if(imageURL.length==0|| [imageURLisEqualToString:@"undefined"]) {
return;
}
NSData*imageData=nil;
if(([imageURLhasPrefix:@"http"])) {
imageData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]] returningResponse:NULL error:NULL];
}else{
NSString*dataString=[[imageURLcomponentsSeparatedByString:@","]lastObject];
imageData=[NSDatadataFromBase64String:dataString];
}
UIImage*image=[UIImageimageWithData:imageData];
if(image) {
[self handleWebViewLongPressWithImageData:imageData];
}
}];
}
这里下载图片的操作可以挪到后面需要的时候做,因为下载慢的话,会堵塞主线程。这样在webView上长按不管是图片链接还是编码的data,都可以自定义地做出处理。