ios swift webview uitouch

ios - Swift-haga clic programáticamente en el punto en la pantalla



webview uitouch (4)

Así que el objetivo era simular un evento de pantalla táctil en un webView.

La estructura es

ViewController- self.glassView-| self.webView-| self.view.

He escrito esta clase pero todavía no pruebo:

class ViewController: UIViewController,UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var glassView: UIView! var portionRect: CGRect! override func viewDidLoad() { super.viewDidLoad() self.webView.delegate = self let url = NSURL (string: "http://www.tiscali.it"); let requestObj = NSURLRequest(URL: url!) self.webView.loadRequest(requestObj) self.view.userInteractionEnabled = true } //////////////////////////////////////////////// // UIWebViewDelegate func webViewDidStartLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webViewDidFinishLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false if self.webView.loading { return } else { simulateTap() } } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func simulateTap() { let pointOnTheScreen = CGPointMake(156.0, 506.6) self.glassView.hitTest(pointOnTheScreen, withEvent: nil) self.glassView.overlapHitTest(pointOnTheScreen, withEvent: nil) print("tap on screen") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { let touchLocation = touch.locationInView(self.view) print("point touched: /(touchLocation)") } super.touchesBegan(touches, withEvent:event) } } extension UIView { func overlapHitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { // 1 if !self.userInteractionEnabled || self.hidden || self.alpha == 0 { return nil } //2 var hitView: UIView? = self if !self.pointInside(point, withEvent: event) { if self.clipsToBounds { return nil } else { hitView = nil } } //3 for subview in self.subviews.reverse() { let insideSubview = self.convertPoint(point, toView: subview) if let sview = subview.overlapHitTest(insideSubview, withEvent: event) { return sview } } return hitView } }

tl; dr- ¿Cómo puedo realizar un toque nativo mediante programación en un punto específico de la pantalla?

Dentro de la vista web hay HTML que contiene un Iframe, por lo que el código y los elementos de la vista web no son accesibles y tampoco es posible el lijado de masajes a JS. Hay un botón en la vista web sobre coordenadas específicas. ¿Cómo puedo presionarlo programáticamente?


Para simular el toque, deberá escribir una función javascript en su página web que pueda hacer clic en el botón en su nombre.

Supongamos que el botón en el sitio web cargado en el iFrame está codificado de la siguiente manera:

<a href="#" id="MagicButton" onclick="targetFunction();">Click Me!</a>

Y el iFrame está codificado como tal en tu página web:

<iframe id="MyIFrame" src="http://www..com" width="200" height="200"></iframe>

En su página web, agregue la siguiente función de javascript para llamar al evento clic en el botón integrado:

<script> function myJavaScriptFunction(){ //get handle for the iFrame element var iFrame = document.getElementById(''MyIFrame''); var htmlDoc = iFrame.contentDocument ? iFrame.contentDocument : iFrame.contentWindow.document; var magicButton = htmlDoc.getElementById(''MagicButton''); magicButton.click(); } </script>

Volviendo a su código Swift, necesitará usar la siguiente API:

func evaluateJavaScript(_ javaScriptString: String, completionHandler completionHandler: ((AnyObject?, NSError?) -> Void)?)

Puede ejecutar su función javascript llamando a la siguiente función después de que la página se haya cargado:

myWKWebview.evaluateJavaScript("myJavaScriptFunction(argument1, argument2);", completion:{ _ in })


Si no desea simular el toque en el nivel de JavaScript, puede usar esta extensión en UITouch y UIEvent , solo UIEvent a Swift:

func performTouchInView(view: UIView) { let touch = UITouch(inView: view) let eventDown = UIEvent(touch: touch) touch.view!.touchesBegan(eventDown.allTouches()!, withEvent: eventDown) touch.setPhase(.Ended) let eventUp = UIEvent(touch: touch) touch.view!.touchesEnded(eventUp.allTouches()!, withEvent: eventUp) }

Su sintaxis puede variar según la versión de Swift que utilice. Estoy haciendo algo de desenvolvimiento forzado aquí, pero deberías tener una idea general de lo que está sucediendo.


También intenta prueba de golpe:

let pointOnTheScreen = CGPointMake(50, 50) view.hitTest(pointOnTheScreen, withEvent: nil)