問題
在WKWebView上的圖片,長按會觸發(fā)系統(tǒng)控件進行保存和共享盏缤,但通過系統(tǒng)共享是沒法分享圖片,只能進行長按手勢覆蓋纳猫,然后用本地控件實現(xiàn)
解決方案
- 屏蔽WebKit的長按邏輯
//禁止長按邏輯
NSMutableString *javascript = [NSMutableString string];
[javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止長按
WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[config.userContentController addUserScript:noneSelectScript];
- 添加長按手勢
-(void)addLongPressGesture
{
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(startLongPress:)];
longPress.delegate = self;
longPress.minimumPressDuration = 0.4f;
longPress.numberOfTouchesRequired = 1;
longPress.cancelsTouchesInView = YES;
[self.locationWebView addGestureRecognizer:longPress];
}
- (void)startLongPress:(UILongPressGestureRecognizer *)pressSender
{
if(pressSender.state == UIGestureRecognizerStateBegan){
//實現(xiàn)相關(guān)功能
[self detectInWebView:pressSender];
DebugLog(@"1. 開始長按手勢");
}else if(pressSender.state == UIGestureRecognizerStateEnded){
//可以添加你長按手勢執(zhí)行的方法,不過是在手指松開后執(zhí)行
DebugLog(@"2. 結(jié)束長按手勢");
}else if(pressSender.state == UIGestureRecognizerStateChanged){
//在手指點下去一直不松開的狀態(tài)執(zhí)行
DebugLog(@"3. 長按手勢改變");
}
}
- 手勢中捕捉圖片進行處理
- (void)detectInWebView:(UIGestureRecognizer *)ges{
CGPoint touchPoint = [ges locationInView: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];
[self.locationWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary*resultDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString* imageURL = resultDic[@"url"];
if(imageURL.length==0|| [imageURL isEqualToString:@"undefined"]) {
return;
}
NSData* imageData=nil;
if(([imageURL hasPrefix:@"http"])) {
imageData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]] returningResponse:NULL error:NULL];
}else{
NSString*dataString = [[imageURL componentsSeparatedByString:@","]lastObject];
// imageData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
imageData = [[NSData alloc] initWithBase64EncodedString:dataString options:NSDataBase64DecodingIgnoreUnknownCharacters];
}
UIImage*image=[UIImage imageWithData:imageData];
if(image) {
//彈框處理
[self.webModel popoverImageAlertWithImage:image Controller:self];
}
}];
}