开发者

How to check whether app is running using [[NSAppleScript alloc] initWithSource:

This is my original script. It will return the current url of Safari

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

What if I want to check whether the Safari browser is open or not before asking the script to return the URL?

Here is how I do in applescript editor.. So this scr开发者_运维技巧ipt will check whether the Safari is running or not.. This works in applescript editor

tell application "Safari"
        if it is running then

            //return url code here
        end if
    end tell

What I need now is to straight away called the script from my cocoa app by using ' [[NSAppleScript alloc] initWithSource:'

I've tried this but its not working

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


Why would that work? It's bad AppleScript grammar.

There are ways to do this without resorting to AppleScript, but it'll do for now. You can have multiple lines in an embedded script by using the C escape sequence \n to insert a newline:

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

You can also break up a string constant by placing one right after another, which makes it easier to read:

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

The C compiler will glue these string constants together into a single NSString object.


The OP's AppleScript one liner code is wrong. The AppleScript text in this should work:

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


As dougscripts (+1) has pointed out but I wanted to make it little bit clearer of why the one liner Applescript syntax within the NSAppleScript the OP tried did not work.

And to be honest I did suggest an edit which lost out three to two

The OP's NSAppleScript code:

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

Did not work because the syntax is wrong. 

The correct syntax should be:

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

There are two changes within part of the code shown in bold below.

\"Safari\" to if it is running then return URL

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜