Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell which device I'm on in Xcode UI Testing?

While an Xcode UI Test is running, I want to know which device/environment is being used (e.g. iPad Air 2, iOS 9.0, Simulator).

How can I get this information?

like image 395
Senseful Avatar asked Aug 30 '15 16:08

Senseful


4 Answers

Using Swift 3 (change .pad to .phone as necessary):

if UIDevice.current.userInterfaceIdiom == .pad {
    // Ipad specific checks
}

Using older versions of Swift:

UIDevice.currentDevice().userInterfaceIdiom
like image 190
cakes88 Avatar answered Oct 18 '22 19:10

cakes88


Unfortunately there is no direct way of querying the current device. However you can work around by querying the size classes of the device:

private func isIpad(app: XCUIApplication) -> Bool {
    return app.windows.elementBoundByIndex(0).horizontalSizeClass == .Regular && app.windows.elementBoundByIndex(0).verticalSizeClass == .Regular
}

As you can see in the Apple Description of size classes, only iPad devices (currently) have both vertical and horizontal size class "Regular".

like image 21
j0nes Avatar answered Oct 18 '22 21:10

j0nes


You can check using the windows element frame XCUIApplication().windows.element(boundBy: 0).frame and check the device type.

You can also set an extension for XCUIDevice with a currentDevice property:

/// Device types
public enum Devices: CGFloat {

    /// iPhone
    case iPhone4 = 480
    case iPhone5 = 568
    case iPhone7 = 667
    case iPhone7Plus = 736

    /// iPad - Portraite
    case iPad = 1024
    case iPadPro = 1366

    /// iPad - Landscape
    case iPad_Landscape = 768
    case iPadPro_Landscape = 0
}

/// Check current device
extension XCUIDevice {
    public static var currentDevice:Devices {
        get {
            let orientation = XCUIDevice.shared().orientation

            let frame = XCUIApplication().windows.element(boundBy: 0).frame

            switch orientation {
            case .landscapeLeft, .landscapeRight:
                return frame.width == 1024 ? .iPadPro_Landscape : Devices(rawValue: frame.width)!
            default:
                return Devices(rawValue: frame.height)!
            }
        }
    }
}

Usage

let currentDevice = XCUIDevice.currentDevice

like image 5
Tal Zion Avatar answered Oct 18 '22 20:10

Tal Zion


Maybe someone would be come in handy the same for XCTest on Objective C:

// Check if the device is iPhone
if ( ([[app windows] elementBoundByIndex:0].horizontalSizeClass != XCUIUserInterfaceSizeClassRegular) || ([[app windows] elementBoundByIndex:0].verticalSizeClass != XCUIUserInterfaceSizeClassRegular) ) {
    // do something for iPhone
}
else {
    // do something for iPad
}
like image 2
Yulia Avatar answered Oct 18 '22 21:10

Yulia