I have browser in my app when for which I am using WKWebView. All I want when user long pressed on image I wanna show custom action sheet instead default alert and also when user tapped on download I should be downloaded in app instead of user gallery. I tried different ways none is working exactly as I want below is my code using long press gesture from this code I can get some of images and for some of images its generate error which says
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SecurityError: The operation is insecure., WKJavaScriptExceptionColumnNumber=198, WKJavaScriptExceptionSourceURL=https://www.google.com/search?q=go&prmd=vni&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj9rKbv3uT9AhXlR_EDHeCxDLMQ_AUoA3oECAIQAw&biw=393&bih=588&dpr=3#imgrc=R7mqldixWHBs7M&imgdii=FBBt5tzUNeKRwM, NSLocalizedDescription=A JavaScript exception occurred}
Below is my code which I tried to get images:
@objc func webViewLongPressed(_ sender: UILongPressGestureRecognizer) {
longpress = true
if sender.state == .ended {
print("Long press Ended")
let tapLocation = sender.location(in: webView)
let scaleFactor = webView.frame.width / webView.scrollView.contentSize.width
let convertedTapLocation = CGPoint(x: tapLocation.x * scaleFactor, y: tapLocation.y * scaleFactor)
webView.evaluateJavaScript("var c = document.createElement('canvas'); var ctx = c.getContext('2d'); var img = document.elementFromPoint(\(convertedTapLocation.x), \(convertedTapLocation.y)); ctx.drawImage(img, 0, 0); var value = c.toDataURL(); value.split(',')[1];") { (result, error) in
if let imageBase64 = result as? String {
let imageData = Data(base64Encoded: imageBase64, options: [])
let selectedImage = UIImage(data: imageData!)
self.imageView.image = selectedImage
}
}
} else if sender.state == .began {
print("Long press detected.")
}
}
can someone please tell me where I am wrong or any other approach for doing this. help will be appreciated Thanks :)