Create a new Safari Browser session on iPhone every time the test is re-run

In my appium mobileweb test automation project (Appium v3.2, JDK 21) with real devices like Android with Chrome browser ( Android v16.0 Samsung Galaxy S21 FE, Chrome v147.0), and iOS(v.26.4.2, iphone 11) with Safari browser, particularly while using iPhone device a new browser session is NOT being used. Meaning in a previous test session, say the test failed in the middle with out being logged out or WebDriver being quit, just the browser session is closed.
For the next test session, the browser (In this case the Safari browser) is starting at the same place the old session has stopped and since it is not finding the correct web elements to login on this old page, it was failing obviously.

I am using the following Java code set up to initiate the IOSDriver.

Please look in to enhancing the Java code to initiate a brand new browser session each time a test is re-launched.

case "iOS":

try {

XCUITestOptions iOsOptions = new XCUITestOptions();

iOsOptions.setPlatformName(platform);

iOsOptions.setPlatformVersion(platformVersion);

iOsOptions.setDeviceName(deviceName);

iOsOptions.setAutomationName("XCUITest");

iOsOptions.setNoReset(false); // or just omit; false is the default

iOsOptions.setUdid(udId);

iOsOptions.setCapability("appium:safariInitialUrl", url);

iOsOptions.setCapability("browserName", browser);

iOsOptions.setCapability("appium:autoAcceptAlerts", true); // accept all alerts

iOsOptions.setCapability("appium:showXcodeLog", true);//display the output of the Xcode command used to run the tests

//Timeout capabilities added to avoid session creation failure

iOsOptions.setCapability("appium:newCommandTimeout", 300);

iOsOptions.setCapability("appium:wdaLaunchTimeout", 120000);

iOsOptions.setCapability("appium:wdaConnectionTimeout", 120000);

iOsOptions.setCapability("appium:useNewWDA", false);//change to true, to force clean WDARunner

iOsOptions.setCapability("appium:safariIgnoreFraudWarning", true);

iOsOptions.setCapability("appium:safariAllowPopups", true);

 

//Timeout capabilities

//Safari specific capabilities

iOsOptions.setCapability("appium:nativeWebTap", false); // // uses JavaScript-based taps,otherwise native(flaky taps in Safari)

 

driver = new IOSDriver(url, iOsOptions);

} catch (Exception e) {

System.out.println("Exception during returning the IOSDriver");

e.printStackTrace();

}

break;

default:

throw new Exception("invalid platform-"+platform+",browswer-"+browser);

}

just add

optionsXCUITest.setForceAppLaunch(true)