Cocoa如何访问剪贴板?

阅读 4.4k
1 个回答

从 so 上找到了段代码,应该能解决 lz 的问题

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Create a background task identifier
    __block UIBackgroundTaskIdentifier task; 
    task = [application beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"System terminated background task early"); 
        [application endBackgroundTask:task];
    }];

    // If the system refuses to allow the task return
    if (task == UIBackgroundTaskInvalid)
    {
        NSLog(@"System refuses to allow background task");
        return;
    }

    // Do the task
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSString *pastboardContents = nil;

        for (int i = 0; i < 1000; i++) 
        {
            if (![pastboardContents isEqualToString:[UIPasteboard generalPasteboard].string]) 
            {
                pastboardContents = [UIPasteboard generalPasteboard].string;
                NSLog(@"Pasteboard Contents: %@", pastboardContents);
            }

            // Wait some time before going to the beginning of the loop
            [NSThread sleepForTimeInterval:1];
        }

        // End the task
        [application endBackgroundTask:task];
    });
}

这么做的风险就是你不知道你的 App 什么时候就被用户给咔嚓了,然后就什么都收不到了。更好的方式是越狱,然后 hook 访问剪切板的相关函数,对感兴趣的内容做出响应。

Grabbing the UIPasteboard like Pastebot while running in the background
苹果文档,关于后台任务执行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进