How to open url in Safari and the get back to the app under UITests in Xcode 7?
Asked Answered
S

3

17

This is my custom view where "LondonStreet" is a button.

enter image description here

When I tap that button I get url and open it in Safari (it works). Then I can go back, using "Back to Wishlist" button (it also works).

enter image description here

The problem is when I try to test this under UITests.

itemsTable.cells.elementBoundByIndex(0).buttons["addressButton"].tap() //press the button to open link in Safari

Along with this line:

app.statusBars.buttons["Back to Wishlist"].tap() //go back, doesn't work, although it was recorded by Xcode itself.

is an error:

UI Testing Failure - Failed to get screenshot within 5s.

And also in issue Navigator

UI Testing failure - Unable to update application state promptly.

enter image description here

Staphylo answered 11/9, 2015 at 11:32 Comment(0)
T
54

Starting in iOS 11 you can interact with other applications using the XCUIApplication(bundleIdentifier:) initializer.

To get back to your app you'd do something like:

let myApp = XCUIApplication(bundleIdentifier: "my.app.bundle.id")
let safari = XCUIApplication(bundleIdentifier: "com.apple.mobilesafari")

// Perform action in your app that opens Safari

safari.wait(for: .runningForeground, timeout: 30)
myApp.activate() // <--- Go back to your app
Thomey answered 25/10, 2017 at 18:36 Comment(5)
answer is awesome;)Ballast
With Xcode 13 and iOS 15 this seems to fail intermittently Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid pid -1'Seraph
@Seraph Having same issue as wellDurian
Same issue here. Xcode 13 on iOS 15 simulator - for some reason test runner sometimes crashes on wait method.Confiscate
@Seraph Try terminating the safari app at the beginning of each test. Resolved the 'Invalid pid -1' crashes in our tests.Cheryl
G
7

UI Testing cannot interact with anything outside of your application. In your scenario, the framework can no longer do anything once your app opens Safari.

To verify this, try printing out the app's hierarchy once Safari opens. You will notice that nothing in Safari nor the navigation bar will show up - you will only see your app's information.

print(XCUIApplication().debugDescription)
Gluttonize answered 11/9, 2015 at 12:50 Comment(1)
This (my) comment no longer applies in iOS 11+ :)Gluttonize
G
2

To open specific url in Safari on iOS 15:

safari.textFields["Address"].tap()
safari.textFields["Address"].typeText("www.urlToOpen.com")
safari.keyboards.buttons["Go"].tap()
Gascon answered 6/1, 2022 at 6:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.