Search code examples
iosxcodeios-simulatorxcode-ui-testing

Is it possible to "toggle software keyboard" via the code in UI test?


I have UI tests which testing login functionality (and uses it to test other stuff), but sometimes when focus is changed from one field to another - the keyboard hides, and although the cursor is blinking in the field, I getting error on field.typeText - no focused fields to fill.

Somehow I realized, that clicking on a Hardware -> Keyboard -> toggle software keyboard makes keyboard to persist on the screen, so test is works well. But I need to make it working on any testing device, on any developer machine, so I want to set this option programmatically without annoying "if test fails, go to … and set … by hand" in readme of the project.

Is it possible?


Solution

  • The simulator's .plist file changed to add support for multiple simulators. The ConnectHardwareKeyboard boolean is now nested underneath the device's UDID. Luckily this UDID is also stored in the plist file. You can add this code using 'run script' under your UITest target's build phases.

    Xcode 9 answer:

    #grab the UDID from the plist
    UDID=$(defaults read com.apple.iphonesimulator CurrentDeviceUDID)
    
    #overwrite the existing value with false
    #OR if the plist doesn't have that value add it in
    /usr/libexec/PlistBuddy -c "Set :DevicePreferences:$UDID:ConnectHardwareKeyboard 
    false" ~/Library/Preferences/com.apple.iphonesimulator.plist 
    || 
    /usr/libexec/PlistBuddy -c  "Add :DevicePreferences:$UDID:ConnectHardwareKeyboard
    bool false" ~/Library/Preferences/com.apple.iphonesimulator.plist
    

    Or you can use this other code to affect all simulators:

    /usr/libexec/PlistBuddy -c "Print :DevicePreferences" ~/Library/Preferences/com.apple.iphonesimulator.plist | perl -lne 'print $1 if /^    (\S*) =/' | while read -r a; do /usr/libexec/PlistBuddy -c "Set :DevicePreferences:$a:ConnectHardwareKeyboard
    false" ~/Library/Preferences/com.apple.iphonesimulator.plist || /usr/libexec/PlistBuddy -c  "Add :DevicePreferences:$a:ConnectHardwareKeyboard
    bool false" ~/Library/Preferences/com.apple.iphonesimulator.plist; done