Saturday, March 18, 2023
HomeiOS Developmentjavascript - The right way to obtain photos from WKWebView to app...

javascript – The right way to obtain photos from WKWebView to app not in person gallery iOS swift

I’ve browser in my app when for which I’m utilizing WKWebView. All I need when person lengthy pressed on picture I wanna present customized motion sheet as a substitute default alert and likewise when person tapped on obtain I must be downloaded in app as a substitute of person gallery. I attempted alternative ways none is working precisely as I need beneath is my code utilizing lengthy press gesture from this code I can get a few of photos and for a few of photos its generate error which says

Error Area=WKErrorDomain Code=4 “A JavaScript exception occurred” UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SecurityError: The operation is insecure., WKJavaScriptExceptionColumnNumber=198, WKJavaScriptExceptionSourceURL=, NSLocalizedDescription=A JavaScript exception occurred}

Beneath is my code which I attempted to get photos:

  @objc func webViewLongPressed(_ sender: UILongPressGestureRecognizer) {
        longpress = true
        if sender.state == .ended {
            print("Lengthy press Ended")
            let tapLocation = sender.location(in: webView)
            let scaleFactor = webView.body.width / webView.scrollView.contentSize.width
            let convertedTapLocation = CGPoint(x: tapLocation.x * scaleFactor, y: tapLocation.y * scaleFactor)
            webView.evaluateJavaScript("var c = doc.createElement('canvas'); var ctx = c.getContext('2nd'); var img = doc.elementFromPoint((convertedTapLocation.x), (convertedTapLocation.y)); ctx.drawImage(img, 0, 0); var worth = c.toDataURL(); worth.break up(',')[1];") { (consequence, error) in
                if let imageBase64 = consequence as? String {
                    let imageData = Information(base64Encoded: imageBase64, choices: [])
                    let selectedImage = UIImage(information: imageData!)
                    self.imageView.picture = selectedImage

        } else if sender.state == .started {
            print("Lengthy press detected.")

can somebody please inform me the place I’m flawed or another strategy for doing this.
assist will likely be appreciated Thanks 🙂


Most Popular