webView与APP

iOS、长按webView 保存图片

2017-12-19  本文已影响998人  凸阿滨

步骤:

1、创建手势

2、监听手势,获取到点击的point

3、根据webview js代码:Document.elementFromPoint(x,y).src 拿到image的src标签,并且通过stringByEvaluatingJavaScriptFromString转换为url的字符串

4、给url做非空判断,有值时 弹出提示框,然后下载图片,通过UIImageWriteToSavedPhotosAlbum保存到相册

关键代码:一、

- (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:@"保存图片到相册"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];

}

上一篇下一篇

猜你喜欢

热点阅读