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 script 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.