在后台接收UIPasteboard(generalPasteboard)通知

NuB*_*Bie 11 cocoa-touch uipasteboard generalpasteboard

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

我用过两个:

[[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(pasteboardNotificationReceived:) 
    name:UIPasteboardChangedNotification 
    object:[UIPasteboard generalPasteboard]];
Run Code Online (Sandbox Code Playgroud)

和:

[[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(pasteboardNotificationReceived:) 
    name:UIPasteboardChangedNotification 
    object:nil ];
Run Code Online (Sandbox Code Playgroud)

注册我的处理程序.

Hil*_*ell 11

我有同样的问题.根据属性的UIPasteboard类参考文档changeCount(重点是我的):

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

我读过这个意思是说我的应用程序会UIPasteboardChangedNotification在我的应用程序重新激活后收到通知.然而,仔细阅读会发现只有在changeCount重新激活应用程序时才会更新.

我通过跟踪changeCount我的应用程序委托中的粘贴板changeCount并在应用程序在后台时发现已更改时发布预期通知来处理此问题.

在app delegate的界面中:

NSUInteger pasteboardChangeCount_;
Run Code Online (Sandbox Code Playgroud)

在app delegate的实现中:

- (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]];
  }
}
Run Code Online (Sandbox Code Playgroud)