Xcode 粘贴数据或CMD V模拟的替代方案
我曾经模拟CMD V事件将数据从我的应用程序粘贴到活动应用程序。然而,新的沙箱限制似乎不再允许这样做了Xcode 粘贴数据或CMD V模拟的替代方案,xcode,macos,cocoa,Xcode,Macos,Cocoa,我曾经模拟CMD V事件将数据从我的应用程序粘贴到活动应用程序。然而,新的沙箱限制似乎不再允许这样做了 有人知道调用粘贴的其他方法吗?您可以使用AppleScript: set the clipboard to "MyString" tell application "System Events" keystroke "v" using {command down} end tell 在cocoa应用程序中,您可以使用NSAppleScript运行脚本。假设您的应用程序资源文件夹中有一
有人知道调用粘贴的其他方法吗?您可以使用AppleScript:
set the clipboard to "MyString"
tell application "System Events"
keystroke "v" using {command down}
end tell
在cocoa应用程序中,您可以使用NSAppleScript
运行脚本。假设您的应用程序资源文件夹中有一个名为Script.txt的文件,如下所示:
tell application "System Events"
keystroke "v" using {command down}
end tell
然后可以使用以下代码:
- (void)pasteInActiveApp:(NSData *)data type:(NSString *)type
{
NSPasteboardItem *item = [[NSPasteboardItem alloc] init];
[item setData:data forType:type];
NSPasteboard *pboard = [NSPasteboard generalPasteboard];
[pboard clearContents];
[pboard writeObjects:@[item]];
NSDictionary *errorDict = nil;
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:[self pasteScript]];
NSAppleEventDescriptor *result = [script executeAndReturnError:&errorDict];
// Handle result
}
- (NSString *)pasteScript
{
static NSString *script;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSError *error;
script = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"Script" withExtension:@"txt"] encoding:NSUTF8StringEncoding error:&error];
if (error) {
// Handle error
}
});
return script;
}
现在,您需要做的就是调用pasteInActiveApp:type:
方法,其中包含要粘贴的数据和粘贴板类型
另一方面,我认为将后台运行的应用程序中的内容粘贴到前台的应用程序中不是一个好主意。首先,你不知道你将它粘贴到哪个应用程序,即使你知道,你也永远不知道你将它粘贴到哪里。用户的浏览器可能具有具有多个输入字段(或类似字段)的表单。此外,用户可能不希望您这样做
编辑:更改代码,以便在Objective-C代码而不是apple脚本中设置数据