Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

ios - Quote-related error when trying to run a shell script via AppleScript inside of Swift code

I'm writing an AppleScript that I'm going to run in a macOS app. This script works fine in Script Editor but when I bring it into Xcode and try to run it, encoding a URL fails with an error about quotation marks.

I'd love any tips to get this to run successfully via Swift and Xcode rather than just Script Editor. Thanks!

My code:

        var source = """
        on encode(str)
            do shell script "php -r 'echo urlencode("" & str & "");'"
        end encode

        set f to encode("https://twitter.com")
        f
        """
        let script = NSAppleScript(source: source)!
        var error: NSDictionary? = nil
        let result = script.executeAndReturnError(&error)

        print(result.stringValue)
        print(error)

Error prints out:

Optional({
    NSAppleScriptErrorBriefMessage = "Expected end of line but found U201c"U201d.";
    NSAppleScriptErrorMessage = "Expected end of line but found U201c"U201d.";
    NSAppleScriptErrorNumber = "-2741";
    NSAppleScriptErrorRange = "NSRange: {60, 1}";
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Quoting strings in shell scripts can be annoying.

Try this, quoted form of looks for the best combination

do shell script "php -r " & quoted form of ("echo urlencode(" & quote & str & quote & ");")

By the way NSRange: {60, 1} tells you where the error occurs (the 61st character in the string)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...