热修复 'Can’t make {button returned:"Connect", text returned:"test"} into type Unicode text.'

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

我正在尝试创建一个小型自动化应用程序,以通过可能隐藏网络的 ssh'd 设备上的终端连接到无线网络。

一系列选项导致一个选项,只需输入 SSID 并让设备连接。

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

我希望它连接到输入的 SSID,在本例中为 "test",但我收到错误消息:

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

display dialog returns 一条记录 {button returned, text returned} 作为错误状态。

要使用 text returned 的值,您必须编写

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

但是您的代码中存在一些冗余,例如按下 Cancel 按钮会立即中止脚本。

代码可以简化为

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

甚至可能没有 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
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
        
        beep
    end if
    
end if