Swift - programmatically click on point in screen

Luda picture Luda · Jun 28, 2016 · Viewed 11.8k times · Source

tl;dr- How can I programmatically perform a native touch in specific point on the screen?

Within the web view there is HTML that contains an Iframe, so the web view code and elements are not accessible and sanding massages to JS is not possible either. There is a button in the web view on specific coordinates. How can I press it programmatically?

Answer

JAL picture JAL · Jun 30, 2016

If you don't want to simulate the touch on the JavaScript level, you can use this extension on UITouch and UIEvent, just bridge it to 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)
}

Your syntax may vary depending on the version of Swift you use. I'm doing some forced-unwrapping here but you should get the general idea of what is happening.