2010-11-21 119 views
10

有没有办法做到这一点?我在启动时注册我的对象UIPasteboardChangedNotification,但是当它发送到后台并打开(例如)Safari并复制一些文本时,我的处理程序永远不会被调用。 (我现在只用模拟器)。在后台接收UIPasteboard(generalPasteboard)通知

我用两个:

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

和:

[[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(pasteboardNotificationReceived:) 
    name:UIPasteboardChangedNotification 
    object:nil ]; 

登记自己的处理程序。

+0

你有没有得到这个解决?我也试图做到这一点。 http://cl.ly/69a4如果你找到了答案,你愿意介意与我分享吗? – Frankrockz 2011-04-20 16:45:04

回答

11

我有同样的问题。根据UIPasteboard Class Reference文档的changeCount属性(强调的是矿):

每当此特性的纸板变化-具体地,当被添加纸板项,修改或删除-UIPasteboard递增值的内容。在增加更改计数后,UIPasteboard会发布名为UIPasteboardChangedNotification(用于添加和修改)和UIPasteboardRemovedNotification(用于删除)的通知。 ...当应用程序重新激活并且另一个应用程序更改了剪贴板内容时,该课程还会更新更改计数当用户重新启动设备时,更改计数将重置为零。

我读过这意味着我的应用程序在我的应用程序重新激活后会收到UIPasteboardChangedNotification通知。但仔细阅读后发现,只有在应用重新激活时才会更新changeCount

我通过跟踪我应用程序委托中的粘贴板changeCount并发布预期通知时发现changeCount在应用程序处于后台时发生了更改。

在应用程序委托的接口:

​​

而在应用程序委托的实现:

- (BOOL)application:(UIApplication*)application 
    didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { 
    [[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]]; 
    } 
} 
+0

它的工作原理但是这个解决方案无法在您的应用程序处于后台时监控通知,它只会在您响应您的应用程序时触发。 – 2012-05-30 04:07:21