简体   繁体   中英

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}";
})

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM