0%
- 刚开始拿到需求的第一反应是:H5页面还可以保存图片??
- 随即想了一下,好像微信里好多H5页面都有这样的功能
- 然后查阅了一下相关资料,有咨询了前端大神发现两行核心代码
1 2 3 4 5 6 7
|
let urlString = "document.elementFromPoint(\(touchPoint.x), \(touchPoint.y)).src"
let saveUrl = webView.stringByEvaluatingJavaScriptFromString(urlString)
|
下面来一起啊看一下完整的代码步骤
首先给UiWebView加一个长按手势
1 2 3 4 5 6 7
|
let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressedGesture(_:)))
longPressGes.delegate = self webView.addGestureRecognizer(longPressGes)
|
实现代理方法
1 2 3 4 5 6
|
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true }
|
接着在手势响应方法里面实现相应的功能
- 注意:
- 一定要判断手势的state属性
- 判断saveUrl是否是一个nil值
1 2 3 4 5 6 7 8 9 10 11 12 13
| @objc func longPressedGesture(recognizer: UILongPressGestureRecognizer){ if recognizer.state != .Began { return }
let touchPoint = recognizer.locationInView(webView)
//核心代码 let urlString = "document.elementFromPoint(\(touchPoint.x), \(touchPoint.y)).src" if let saveUrl = webView.stringByEvaluatingJavaScriptFromString(urlString) { //判断图片的链接是否为空,长度是否为o if saveUrl.characters.count == 0 { return } addAlertAction(saveUrl) } }
|
调用保存图片功能按钮
1 2 3 4 5 6 7 8 9 10 11 12
| fileprivate func addAlertAction(imageStr: String){ let alertV = UIAlertController() let saveAction = UIAlertAction(title: "保存图片", style: .Default) { (alertV) in self.saveImageToPhoto(imageStr) } let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
alertV.addAction(saveAction) alertV.addAction(cancelAction) controller.presentViewController(alertV, animated: true, completion: nil) }
|
使用SDWebImage保存图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| fileprivate func saveImageToPhoto(imageStr: String){ guard let imageUrl = NSURL(string: imageStr) else { return }
let sdManager = SDWebImageManager.sharedManager()
var image : UIImage! if sdManager.diskImageExistsForURL(imageUrl) { image = sdManager.imageCache.imageFromDiskCacheForKey(imageUrl.absoluteString)
}else{ let data = NSData(contentsOfURL: imageUrl) image = UIImage(data: data!) }
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) }
|
最后是一个保存成功与否的回调方法
1 2 3 4 5 6 7 8
| func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) { if didFinishSavingWithError != nil { MBProgressHUD.show(string: "请开启访问相册权限后使用此功能", inView: self.view) } else { MBProgressHUD.show(string: "图片保存成功", inView: self.view) } }
|
以上如有不妥之处还望多多指正