Problem with NSAppleScript execution
Problem with NSAppleScript execution
- Subject: Problem with NSAppleScript execution
- From: Nava Carmon <email@hidden>
- Date: Mon, 12 Sep 2011 18:50:13 +0300
Hi list,
I'm trying to run a simple Apple script, that gets the text from the frontmost application. Basically it simulates cmd+c click. It checks whether the clipboard is empty and if it is, it simulates the cmd+a and then cmd+c again.
It doesn't work consistently. Sometimes it works and sometimes - doesn't. The interesting thing is that it doesn't return any error. Like the script runs and even returns a descriptor, but I see the data is 0 bytes there.
Same script in the ScriptEditor btw works just fine :(
Did somebody bump into such a thing before?
Here is the code, which I use:
NSString *scriptStr = @"set the clipboard to \"\"\n"
"tell application \"System Events\" to keystroke \"c\" using command down\n"
"delay 0.1\n"
"set selected_text to (the clipboard as text)\n"
"if length of selected_text = 0 then\n"
"tell application \"System Events\" to keystroke \"a\" using command down\n"
"delay 0.1\n"
"tell application \"System Events\" to keystroke \"c\" using command down\n"
"delay 0.1\n"
"end if\n"
"set selected_text to (the clipboard as text)\n"
"return selected_text";
appleScript = [[NSAppleScript alloc] initWithSource:scriptStr];
NSLog(@"appleScript = %@", appleScript.source);
NSString *returnString = nil;
@try
returnDescriptor = [appleScript executeAndReturnError:&errors];
if (errors) {
NSArray *all = [errors allValues];
for (int i = 0; i < [all count]; i++)
NSLog(@"ERROR ****** %@\n", (NSString *)[all objectAtIndex:i]);
}
if (returnDescriptor != NULL) {
if (kAENullEvent != [returnDescriptor descriptorType]) {
if (cAEList != [returnDescriptor descriptorType]){
NSData *aData = [returnDescriptor data];
if (aData && [aData length] != 0) {
returnString = [[[NSString alloc] initWithCharacters:[aData bytes]
length:[aData length]/2] autorelease];
}
}
} else {
NSLog(@"%@", @"Couldn't process AppleScript");
}
}
NSLog(@"copied string = %@", returnString);
}
@catch (NSException * e) {
NSLog(@"exception = %@", [e description]);
}
return returnString;
The returnDescriptor isn't NULL, but has 0 bytes of data. It's like something doesn't work there and the script isn't performed.
More than that, when I run same script from Script editor, it works perfect. Is it a known problem or do I do something wrong?
Thanks,
Nava
Nava Carmon
email@hidden
"Think good and it will be good!"
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden