iOS webView长按保存图片
#import <Photos/Photos.h>
遵守代理:UIGestureRecognizerDelegate
在webView的懒加载里加上以下代码
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userController = [[WKUserContentController alloc] init];
configuration.userContentController = userController;
//禁止长按逻辑
NSMutableString *javascript = [NSMutableString string];
[javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[configuration.userContentController addUserScript:noneSelectScript];
// 实现长按事件的方法
-(void)addLongPressGesture
{
//添加手势前把3d Touch的移除掉,不然有些机型因为3D Touch不能长按保存
for (UIView* subview in self.webView.scrollView.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"WKContentView")]) {
for (UIGestureRecognizer* longPress in subview.gestureRecognizers) {
if ([longPress isKindOfClass:UILongPressGestureRecognizer.class]) {
[subview removeGestureRecognizer:longPress];
}
}
}
}
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(startLongPress:)];
longPress.delegate = self;
longPress.minimumPressDuration = 0.4f;
longPress.numberOfTouchesRequired = 1;
longPress.cancelsTouchesInView = YES;
[self.webView addGestureRecognizer:longPress];
}
- (void)startLongPress:(UILongPressGestureRecognizer *)pressSender
{
if(pressSender.state == UIGestureRecognizerStateBegan){
//实现相关功能
[self detectInWebView:pressSender];
// DebugLog(@"1. 开始长按手势");
}else if(pressSender.state == UIGestureRecognizerStateEnded){
//可以添加你长按手势执行的方法,不过是在手指松开后执行
// DebugLog(@"2. 结束长按手势");
}else if(pressSender.state == UIGestureRecognizerStateChanged){
//在手指点下去一直不松开的状态执行
// DebugLog(@"3. 长按手势改变");
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self addLongPressGesture];
}
- (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.webView 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) {
__weak typeof(self) weakSelf = self;
[TBNOAlertView showAlertView:@"提示" msg:@"保存到相册" sureTitle:@"保存" canTitle:@"取消" sureBlock:^{
//判断相册权限
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusRestricted ||
status == PHAuthorizationStatusDenied) {
[InstanceTool permissionToRemindWithRemindTitle:@"请在ipone的“设置-隐私-相册”选项中,允许访问你的相册" remindType:IAPermissionToRemindTypePhoto];
return;
}
__strong typeof(weakSelf) strongSelf = weakSelf;
[strongSelf loadImageFinished:image];
} cancelBlock:^{
}];
}
}];
}
- (void)loadImageFinished:(UIImage *)image {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// /写入图片到相册
PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
NSLog(@"success = %d, error = %@", success, error);
if(success) {
[TBNOAlertView showAlertView:@"提示" msg:@"保存成功!" sureTitle:@"" canTitle:@"确定" sureBlock:^{
} cancelBlock:^{
}];
}
}];
}
推荐阅读
-
iOS实现图片保存与搜索功能
-
iOS生成二维码(中间包含图片),长按识别二维码(Swift)
-
Android实现点击WebView界面中图片滑动浏览与保存图片功能
-
iOS实现图片保存与搜索功能
-
iOS用WKWebView与JS交互获取系统图片及WKWebView的Alert,Confirm,TextInput的监听代理方法使用,屏蔽WebView的可选
-
Android实现点击WebView界面中图片滑动浏览与保存图片功能
-
iOS 保存图片到相册
-
Android使用webView长按保存下载网络图片
-
一文彻底解决HTML5页面中长按保存图片功能
-
iOS【webView 加载微信文章注入JS实现交互 浏览图片及保存】