hot to fix 'Can’t make {button returned:"Connect", text returned:"test"} into type Unicode text.'

I'm trying to create a little automator app to connect to a wireless network via terminal on an ssh'd device where the network may be hidden.

A series of options leads to an option to simply type in an SSID and have the device connect.

set userSSID to display dialog "Type the SSID for the network you require below" buttons ["Connect", "Cancel"] default answer "" default button 1

            if button returned of result = "Cancel" then
                error number -128

            else

                if button returned of result = "Connect" then

                    tell application "Terminal"
                        set currentTab to do script ("networksetup -setairportpower en1 on")
                        delay 2
                        do script ("networksetup -setairportnetwork en1 '" & userSSID & "'") in currentTab
                    end tell
                end if

I'm expecting it to connect to the SSID as typed in, in this case "test", however I'm getting the error:

The action “Run AppleScript” encountered an error: “Can’t make {button returned:"Connect", text returned:"test"} into type Unicode text.”


Solution 1:

display dialog returns a record {button returned, text returned} as the error states.

To use the value of text returned you have to write

do script ("networksetup -setairportnetwork en1 '" & text returned of userSSID & "'") in currentTab

However there is some redundancy in your code, for example pressing the Cancel button aborts the script immediately.

The code can be reduced to

set {text returned:userSSID} to display dialog "Type the SSID for the network you require below" buttons ["Connect", "Cancel"] default answer "" default button 1
tell application "Terminal"
    set currentTab to do script ("networksetup -setairportpower en1 on")
    delay 2
    do script ("networksetup -setairportnetwork en1 '" & userSSID & "'") in currentTab
end tell

or maybe even without Terminal.app

set {text returned:userSSID} to display dialog "Type the SSID for the network you require below" buttons ["Connect", "Cancel"] default answer "" default button 1
do shell script "networksetup -setairportpower en1 on"
delay 2
do shell script "networksetup -setairportnetwork en1 " & quoted form of userSSID