【问题标题】:How to check whether app is running using [[NSAppleScript alloc] initWithSource:如何使用 [[NSAppleScript alloc] initWithSource 检查应用程序是否正在运行:
【发布时间】:2011-11-11 19:45:57
【问题描述】:

这是我的原始脚本。它将返回 Safari 的当前 url

NSAppleScript *scriptURL= [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" to return URL of front document as string"];

如果我想在要求脚本返回 URL 之前检查 Safari 浏览器是否打开,该怎么办?

这是我在 applescript 编辑器中的操作。所以这个脚本将检查 Safari 是否正在运行。这在 applescript 编辑器中有效

tell application "Safari"
        if it is running then

            //return url code here
        end if
    end tell

我现在需要的是使用' [[NSAppleScript alloc] initWithSource:' 直接从我的可可应用程序中调用脚本

我试过了,但它不起作用

NSAppleScript *scriptURL= [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" if it is running to return URL of front document as string"];

【问题讨论】:

  • 你看过NSRunningApplication吗?这将为您提供所需的信息,而无需借助 AppleScript。

标签: objective-c macos cocoa applescript applescript-objc


【解决方案1】:

为什么会这样?这是糟糕的 AppleScript 语法。

有很多方法可以在不借助 AppleScript 的情况下做到这一点,但现在就可以了。通过使用 C 转义序列 \n 插入换行符,您可以在嵌入式脚本中包含多行:

NSString *source = @"tell application \"Safari\"\nif it is running then\nreturn URL of front document as string\nend if\nend tell";

你也可以通过一个接一个地放置来分解一个字符串常量,这样更容易阅读:

NSString *source =
    @"tell application \"Safari\"\n"
        "if it is running then\n"
            "return URL of front document as string\n"
        "end if\n"
    "end tell";

C 编译器会将这些字符串常量粘合到一个 NSString 对象中。

【讨论】:

    【解决方案2】:

    OP 的 AppleScript 单行代码错误。这里的 AppleScript 文本应该可以工作:

    NSAppleScript *scriptURL= [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" to if it is running then return URL of front document as string"];
    

    【讨论】:

      【解决方案3】:

      正如 dougscripts (+1) 所指出的那样,但我想让它更清楚一点,为什么 OP 尝试的 NSAppleScript 中的单行 Applescript 语法不起作用。

      老实说,我确实提出了一个输掉三比二的编辑

      OP 的 NSAppleScript 代码:

      NSAppleScript *scriptURL= [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" if it is running to return URL of front document as string"];
      

      由于语法错误,无法正常工作。

      正确的语法应该是:

      NSAppleScript *scriptURL= [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" to if it is running then return URL of front document as string"];
      

      下面以粗体显示的部分代码有两个变化。

      \"Safari\" to 如果它正在运行返回 URL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 2016-04-28
        • 2016-07-17
        • 1970-01-01
        相关资源
        最近更新 更多