在后台运行时抓住像Pastebot这样的UIPasteboard

Fra*_*ckz 3 iphone url notifications multitasking uipasteboard

我知道这是可能的,因为Tapbots Pastebot这样做.当我的iPhone应用程序在后台运行时,我试图抓住UIPasteboard并将其添加到UITableView,就像Pastebot一样,但我也试图缩短链接,如果它是一个URL并将其复制回UIPastboard以便它准备就绪供用户粘贴到任何地方.现在,Pastebot通过播放音频文件10分钟显然在后台运行.我在applicationDidFinishLaunching中设置了NSNotificationCenter

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pasteboardChangedNotification:) name:UIPasteboardChangedNotification object:[UIPasteboard generalPasteboard]];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pasteboardChangedNotification:) name:UIPasteboardRemovedNotification object:[UIPasteboard generalPasteboard]];

- (void)pasteboardChangedNotification:(NSNotification*)notification {
pasteboardChangeCount_ = [UIPasteboard generalPasteboard].changeCount; 
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
     if (pasteboardChangeCount_ != [UIPasteboard generalPasteboard].changeCount) {
    [[NSNotificationCenter defaultCenter] postNotificationName:UIPasteboardChangedNotification object:[UIPasteboard generalPasteboard]];
     }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以指点我抓住UIPasteboard并缩短链接,如果它是一个URL并将其发送回UIPasteboard?我已经阅读了多任务开发文档和UIPasteboard文档.如果有人有解决方案,请与我分享?

谢谢

Sim*_*e99 8

我设法实现类似的东西的唯一方法是不打扰NSNotificationCenter而只是UIPasteboard在后台只是定期复制内容.

下面的代码检查UIPasteboard每秒一次,持续一千秒.我相信一个应用程序可以在后台运行大约10分钟而不播放音频.如果您在后台播放音频文件,应用程序可以继续运行.

- (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];
    });


}
Run Code Online (Sandbox Code Playgroud)