iOS 开发 iOS 13 SDK 适配

在后台的时候接收UIPasteboard (generalPas

2016-12-28  本文已影响749人  张嘉夫

根据UIPasteboard Class Reference文档关于 changeCount 属性的部分(重点如下):

无论何时剪贴板的内容改变——特别是剪贴板项目被添加、修改和移除的时候——UIPasteboard增加它的属性值。在它增加计数之后,UIPasteboard会发叫做UIPasteboardChangedNotification的通知(对于添加和修改)和叫做UIPasteboardRemovedNotification的通知(对于移除)。...当一个程序恢复了,另一个程序改变了剪贴板内容的时候也会改变这个数。当用户重启了设备,这个数就重置到零了。

我读了这个,对我的程序来说意味着会收到 UIPasteboardChangedNotification 通知,在app被恢复的时候。很严谨的阅读功底,但是app在被恢复的时候只有changeCount被更新了。

我通过在app delegate中追踪剪贴板的changeCount解决了这个问题,发现app在后台的时候changeCount被改变了就发布期望的通知。

在app delegate的interface里:

NSUInteger pasteboardChangeCount_;

在 app delegate的implementation里:

- (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]];
  }
}
上一篇 下一篇

猜你喜欢

热点阅读