In recent projects, it is required to save pictures in webview, and a pop-up prompt for saving can be realized by long pressing.
The specific implementation is as follows:
Note that since this function needs to save pictures to the album, it requires write permission of the album. The Privacy - Photo Library Additions Usage Description key-value pair needs to be added to the plist file.
func addLongPressGes() {
//添加长按手势
let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressedGesture(recognizer:)))
//一定要遵循代理
longPressGes.delegate = self
webView.addGestureRecognizer(longPressGes)
}
@objc func longPressedGesture(recognizer: UILongPressGestureRecognizer) {
if recognizer.state != .began { return }
let touchPoint = recognizer.location(in: webView)
//核心代码
let urlString = "document.elementFromPoint(\(touchPoint.x), \(touchPoint.y)).src"
if let saveUrl = webView.stringByEvaluatingJavaScript(from: urlString) {
//判断图片的链接是否为空,长度是否为o
if saveUrl.count == 0 { return }
addAlertAction(imageStr: saveUrl)
}
}
fileprivate func addAlertAction(imageStr: String){
let alertV = UIAlertController()
let saveAction = UIAlertAction(title: "保存图片", style: .default) { (alertV) in
self.saveImageToDisk(imageStr)
}
//取消保存不作处理
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertV.addAction(saveAction)
alertV.addAction(cancelAction)
self.present(alertV, animated: true, completion: nil)
}
//保存图片 这里使用了SDWebImage的缓存机制
fileprivate func saveImageToDisk(_ imageStr: String){
guard let imageUrl = URL(string: imageStr) else { return }
let sdManager = SDWebImageManager.shared()
var image : UIImage!
sdManager.cachedImageExists(for: imageUrl) { (isExists) in
if isExists {
//先从缓存中查找图片
image = sdManager.imageCache?.imageFromDiskCache(forKey: imageUrl.absoluteString)
}else {
//缓存中没有图片在进行网络下载
let data = try! Data(contentsOf: imageUrl)
image = UIImage(data: data)
}
//保存图片到相册中
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
@objc func image(_ image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject){
if didFinishSavingWithError != nil {
Toast(text: "请开启访问相册权限后使用此功能").show()
} else {
Toast(text: "图片保存成功").show() //此处的Toast是使用的一个封装的Toast弹框库,具体可按自己的需求进行提示显示。
}
}
Note that the following proxy methods must be implemented:
//不实现该代理方法,长按无效
//MARK: 手势代理方法
extension ViewController : UIGestureRecognizerDelegate{
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
Calling method:
Just call the addLongPressGes() method directly.
The reference address of this article is: https://www.jianshu.com/p/b1073b79d7ea , on which some code modifications have been made.