iOS WKWebView自定义长按保存图片
前言
最近做项目要在APP里加载H5网页后,在打开的网页长按保存网页中的图片问题,使用系统的就可以满足,但系统提供的很不友好,只满足基本的保存图片功能。
系统长按的缺陷
1. 无法监听长按识别的处理
2. 弹出框无法自定义
3. 如用户没有授权相册权限无法提示
4. 保存到相册后无明确提示,只有打开相册查看
经过查阅相关资料实现了WKWebView的长按弹框,保存图片功能 , 下面开始代码部分
1.禁用WKWebView自己的长按
- (WKWebView *)wkWebView {
if (_wkWebView == nil) {
//创建WKWebview配置对象
WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc] init];
config.preferences = [[WKPreferences alloc] init];
config.preferences.minimumFontSize =10;
config.preferences.javaScriptEnabled =YES;
config.preferences.javaScriptCanOpenWindowsAutomatically =NO;
// js代码
NSMutableString *javascript = [NSMutableString string];
[javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
[javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
_wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR_HEIGHT - NAVBAR_HEIGHT) configuration:config];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate = self;
_wkWebView.allowsBackForwardNavigationGestures = NO;
[_wkWebView.configuration.userContentController addUserScript:noneSelectScript];
[self.view addSubview:_wkWebView];
UILongPressGestureRecognizer* longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
longPressed.delegate = self;
[_wkWebView addGestureRecognizer:longPressed];
//这里使用的是js交互的第三方库
_wkBridge = [WKWebViewJavascriptBridge bridgeForWebView:_wkWebView];
[_wkBridge setWebViewDelegate:self];
[self interactionWebSettingUserAgent:_wkWebView];
}
return _wkWebView;
}
2.长按识别手势的处理(因本人项目的前端返回的是base64的图片字符串所以通过判断字符串区分图片)
/// 长按识别
/// @param recognizer 手势
- (void)longPressed:(UILongPressGestureRecognizer*)recognizer
{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [recognizer locationInView:self.wkWebView];
// 获取html的图片地址
NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
// tanNameJs 通过wkwebview获取tagName == img 也可以判断是图片类型
// NSString * tagNameJs = [NSString stringWithFormat:@“ document.elementFromPoint(%f,%f).tagName”,pt.x,pt.y];
@weakify(self);
[self.wkWebView evaluateJavaScript:imgURL completionHandler:^(NSString* data, NSError * _Nullable error) {
@strongify(self);
// 图片
if ([data containsString:@"data:image/"]){
[self showalertImage:data];
}
}];
}
长按无法响应的问题
遵循 UIGestureRecognizerDelegate 代理
/// 多手势开关
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
//只有当手势为长按手势时反馈,非长按手势将阻止。
return [otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]];
}
3.弹出框处理
- (void)showalertImage:(NSString *)data{
// 替换首位空格
data = [data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// 替换空格
data = [data stringByReplacingOccurrencesOfString:@"\r" withString:@""];
// 替换换行符
data = [data stringByReplacingOccurrencesOfString:@"\n" withString:@""];
// 替换html返回的base64的字符串标示 前端返回为 “data:image/jpeg;base64,/sdjfkldjfjdjsll”
data = [data stringByReplacingOccurrencesOfString:@"data:image/jpeg;base64," withString:@""];
// 替换另一种格式(APP分享好友二维码模块也可以保存图片 ,这里进行处理)
data = [data stringByReplacingOccurrencesOfString:@"data:image/png;base64," withString:@""];
// 弹出alert
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
// 保存相册操作
UIAlertAction *saveImage = [UIAlertAction actionWithTitle:@"保存到相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 首先获取权限
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied)
{
[HCProgressHUD showMessage:@"请在设置-隐私-照片,打开访问相册权限"];
return;
}
//请求权限 需每次请求 (可以监听到第一次系统弹出权限的选项)
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
// 这个block块非Main ,这里回到main线程弹出HUD
dispatch_async_on_main_queue(^{
if (status == PHAuthorizationStatusAuthorized) {
// 因html为base64图片 ,这里进行转换图片
NSData *dataImage = [[NSData alloc] initWithBase64EncodedString:data options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *image = [UIImage imageWithData:dataImage];
// 使用PHPhotoLibrary框架保存图片
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 保存图片操作
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
dispatch_async_on_main_queue(^{
// 监听是否成功
if (success) {
[HCProgressHUD showMessage:@"保存图片成功"];
}else{
[HCProgressHUD showMessage:@"保存图片失败"];
}
});
}];
}else{
[HCProgressHUD showMessage:@"请在设置-隐私-照片,打开访问相册权限"];
}
});
}];
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alertVC addAction:saveImage];
[alertVC addAction:cancel];
[self presentViewController:alertVC animated:YES completion:nil];
}