【问题标题】:Quote-related error when trying to run a shell script via AppleScript inside of Swift code尝试在 Swift 代码中通过 AppleScript 运行 shell 脚本时出现与引号相关的错误
【发布时间】:2020-12-31 18:15:10
【问题描述】:

我正在编写要在 macOS 应用程序中运行的 AppleScript。该脚本在脚本编辑器中运行良好,但是当我将它带入 Xcode 并尝试运行它时,对 URL 进行编码失败并出现关于引号的错误。

我很想通过 Swift 和 Xcode 而不仅仅是脚本编辑器成功运行它的任何提示。谢谢!

我的代码:

        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)

错误打印出来:

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

【问题讨论】:

  • 这到底是什么……?!您是否有特殊原因必须 调用 AppleScript 来调用 Bash 来调用 PHP 来对字符串进行 URL 编码,而不是仅使用 NSString.addingPercentEncoding(withAllowedCharacters:…) 这将是非疯狂的方式吗?即使你确实需要为了一些不透明的目的调用 PHP,你也不需要其他的废话;只需使用Swift’s Process 直接运行/usr/bin/php
  • 我对 AppleScript 还很陌生,并没有真正将 Foundation 用作我的脚本的一部分,这就是你的建议,但是是的,这是一种非常奇怪的方法,组合在一起来自过去几年的SO答案。感谢您的反馈
  • SO 是智慧的开始,而不是结束。如果你正在尝试执行一项常见的任务并且它被证明是困难的,那很可能是因为你以最糟糕的方式来完成它,完全错过了所有已经存在的更安全、更简单、更容易、正确的解决方案。成为一名称职的程序员的一半挑战是学会识别当你把自己挖进一个大的哑洞并说:“这不可能是正确的; 必须有更简单的方法。”在这种情况下,要问的正确问题是“如何在 Swift 中对字符串进行 URL 编码?”,从中很容易找到正确的答案。

标签: ios swift xcode applescript


【解决方案1】:

在 shell 脚本中引用字符串可能很烦人。

试试这个,quoted form of 寻找最佳组合

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

顺便NSRange: {60, 1}告诉你错误发生在哪里(字符串中的第61个字符)

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2022-10-08
    • 2011-09-04
    • 2014-05-13
    • 2021-06-09
    相关资源
    最近更新 更多