Generic way to perform TouchActions in the devices using Selenium/Appium.

Perform swipe action on real devices, emulators/simulators irrespective of platform and devices/device size.

Swipe actions in mobile devices

Here, I will walk you through the code which will help you perform gestures on any device irrespective of the platform and device's size.

Device screen dimensions

As you can see for the mobile the origin is on the top left corner of the screen and the width of the device is the x-axis and the height is the y-axis. What we will do here is to play with these x and y values to achieve the gestures.

To start with, let's define the set of pointers according to your swipe action(in percentage). Let's take Swipe Down action first.

SWIPE DOWN

The starting point for the swipe-down action will be 50% of the x-axis (horizontal center of the screen) and 30% of the y-axis and the endpoint will be 50% of the x-axis (horizontal center of the screen) to 80% of the y-axis. These values can be tweaked based on your need. Let's define them in an integer array as shown below:

Now that we have defined the start and end positions for the swipe action, let's get the device dimensions and compute the actual screen position.

To get the device dimension dynamically :

Let's take a device with screen size 1440 x 3120 px, then the x value for the swipe-down action will be 50% * 1440 = 720 and then the y-axis value will be 30% * 3120 and 80% * 3120 which will be 936 and 2496 respectively. The final coordinates for this case will be (720,936) and ( 720,2496).

Now that we have computed the start and the end coordinates for the action all we have to do is perform the swipe.

The function below will compute the screen coordinates for the action :

The swipe method below will perform the touch actions on the device, If you notice :

I have further improvised this by dynamically performing the swipe until the element is visible/matches the expectation condition.

Full code to perform the gesture:

I have made use of something called normalizer in the above script, It is a value ranging from 0 to 1, when you change the normalizer value you can perform actions on different areas of the screen.

Tip: In android, under your “Developer Options” -> Enable “Pointer Location”. This will help you understand how the gesture is getting executed in the devices. I don’t think we have anything equivalent in iOS devices, but appium desktop can help to an extent.

Cheers!

Automation Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store